【问题标题】:How many ways we can pass data (objects) between activities in android?我们可以通过多少种方式在 android 的活动之间传递数据(对象)?
【发布时间】:2014-11-25 09:56:47
【问题描述】:
I hope that we can pass data between android application components
通过以下方式。
1.我们可以使用intent对象传递数据,
2.我们可以通过intent实现serializable、parcelable接口和传递对象,
3.我们可以通过扩展Application类创建一个新类,从任何地方访问全局成员
安卓应用,
4.sharedpreference,
5.sqlite.
还有其他机制可以在 android 应用程序组件之间发送数据吗?
【问题讨论】:
标签:
android
android-intent
serialization
【解决方案1】:
另一个选项是创建 ApplicationPool。
请按照以下步骤操作:-
启动应用程序池:-
ApplicationPool pool = ApplicationPool.getInstance();
修改详情页的数据并添加到池中
pool.put("key", object);
从池中获取列表页上修改后的数据
Object object = (Object) pool.get("key");
重要提示:- 获取数据后通知listview或gridview
ApplicationPool 类文件
public class ApplicationPool {
private static ApplicationPool instance;
private HashMap<String, Object> pool;
private ApplicationPool() {
pool = new HashMap<String, Object>();
}
public static ApplicationPool getInstance() {
if (instance == null) {
instance = new ApplicationPool();
}
return instance;
}
public void clearCollectionPool() {
pool.clear();
}
public void put(String key, Object value) {
pool.put(key, value);
}
public Object get(String key) {
return pool.get(key);
}
public void removeObject(String key) {
if ((pool.get(key)) != null)
pool.remove(key);
}
}
【解决方案2】:
另一种方法是使用静态元素,无论是:
- 静态字段(例如公共访问)
- 静态属性(意味着带有 getter 和/或 setter 的私有字段)
- 单身人士
- 可能是嵌套类
虽然在 OOP 中使用静态变量值得商榷,但它们引入了全局状态,因此也是实现活动之间数据共享的一种方式。
【解决方案3】:
1) WeakReferences的HashMap,例如:
public class DataHolder {
Map<String, WeakReference<Object>> data = new HashMap<String, WeakReference<Object>>();
void save(String id, Object object) {
data.put(id, new WeakReference<Object>(object));
}
Object retrieve(String id) {
WeakReference<Object> objectWeakReference = data.get(id);
return objectWeakReference.get();
}
}
活动开始前:
DataHolder.getInstance().save(someId, someObject);
来自已启动的活动:
DataHolder.getInstance().retrieve(someId);
2)或者奇怪的方法:将数据存储在服务器O_o上