在不同的Activity之间有时需要传递复杂些的数据,可以写如下代码
Activity A:
LinkedHashMap mLinkedHashMap = new LinkedHashMap<String, Object>();
// setting data in map
Bundle bundle = new Bundle();
bundle.putSerializable("OBJECTS_LINKED_HASHMAP", mLinkedHashMap);
Intent intent = new Intent(this, ActivityB.class);
intent.putExtras(bundle);
startActivity(intent);
Activity B:
Bundle bundle = this.getIntent().getExtras();
LinkedHashMap mLinkedHashMap = new LinkedHashMap<String, Object>();
mLinkedHashMap = (LinkedHashMap<String, Object>) bundle.getSerializable("OBJECTS_LINKED_HASHMAP");
但是这样写,会出现空指针的错误,为了解决这个问题可以设一个单例模式:
public class Share {
private static Share current;
public static Share getInstance() {
synchronized (Share.class) {
if(current == null) {
current = new Share();
}
return current;
}
}
final HashMap<String, Object> memoryMap;
public Share() {
memoryMap = new HashMap<String, Object>();
}
public void put(String key, Object value) {
memoryMap.put(key, value);
}
public Object get(String key) {
return memoryMap.get(key);
}
}