简体   繁体   English

如何在活动、序列化或 SingleInstance 之间共享对象?

[英]How to share objects between activites, serialization or SingleInstance?

I have certain data in the data model class and want to share this data/object to the other activity.我在数据模型类中有某些数据,并希望将此数据/对象共享给其他活动。 Single Instance could be a good choice but want to finish my previous activity and hence will got null pointer.单实例可能是一个不错的选择,但想要完成我以前的活动,因此会得到空指针。 Please Suggest the best possible way to do it?请建议最好的方法来做到这一点?

The best practice is to use intent object for that, putting either parcel or serialized data in his extras.最佳实践是为此使用意图对象,将包裹或序列化数据放入他的附加内容中。

Static is dangerous since you must be always prepared for the case in which your application will be killed and restored.静态是危险的,因为您必须始终为应用程序将被终止和恢复的情况做好准备。

Best possible way to use serialization, SingleInstance will not work here because you have to finish your activity.使用序列化的最佳方式, SingleInstance 在这里不起作用,因为您必须完成您的活动。

Intent intent = new Intent(this, B.class);
ArrayList<String> data = new ArrayList<String>();
arrays.add("testing");
intent.putExtra("arrayList", data);
startActivity(intent);

you can use your objects instead of String and other side you can retrieve using this.您可以使用您的对象而不是 String 和其他方面,您可以使用它进行检索。

ArrayList<String> arrayList =(ArrayList<String>) getIntent().getSerializableExtra("arrayList");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM