我有一个活动,它是整个应用程序中使用的主要活动,它有许多变量。我有另外两个活动,我希望能够使用来自第一个活动的数据。 现在我知道我可以这样做:

GlobalState gs = (GlobalState) getApplication();
String s = gs.getTestMe();

然而,我想要分享很多变量,其中一些可能相当大,所以我不想像上面那样创建它们的副本。

是否有一种方法可以直接获取和更改变量而不使用get和set方法?我记得在谷歌开发网站上读过一篇文章,说不建议在Android上使用这种性能。


当前回答

如果你的意图是从当前Activity调用其他Activity,你应该使用intent。您可以将重点放在按需共享数据而不是持久化数据上。

However, if you really need to persist these values then you could persist them in some kind of structured text file or database on local storage. A properties file, XML file, or JSON file could store your data and be easily parsed during activity creation. Don't forget also that you have SQLite on all Android devices, so you could store them in a database table. You could also use a Map to store key-value pairs and serialize the map to local storage, but this might be too cumbersome to be useful for simple data structures.

其他回答

Using the hashmap of weak reference approach, described above, and in http://developer.android.com/guide/faq/framework.html seems problematic to me. How are entire entries reclaimed, not just the map value? What scope do you allocate it in? As the framework is in control of the Activity lifecycle, having one of the participating Activities own it risks runtime errors when the owner is destroyed in advance of its clients. If the Application owns it, some Activity must explicitly remove the entry to avoid the hashmap from holding on to entries with a valid key and a potentially garbaged collected weak reference. Furthermore, what should a client do when the value returned for a key is null?

在我看来,由应用程序拥有或在单例中拥有WeakHashMap是更好的选择。映射中的值是通过键对象访问的,当不存在对键的强引用时(即所有活动都使用键及其映射到的对象完成),GC可以回收映射条目。

你可以扩展Application类并标记任何你想要的对象,然后它们就可以在你的应用程序的任何地方使用

假设你使用Intent从活动一调用活动二。 你可以通过intent.putExtra()传递数据,

拿着这个作为你的参考。 使用Intent.putExtra发送数组

希望这是你想要的。

如果你想处理数据对象,这两个实现非常重要

Serializable和Parcelable

Serializable is a marker interface, which implies the user cannot marshal the data according to their requirements. So when object implements Serializable Java will automatically serialize it. Parcelable is android own serialization protocol. In Parcelable, developers write custom code for marshaling and unmarshaling. So it creates less garbage objects in comparison to Serialization The performance of Parcelable is very high when comparing to Serializable because of its custom implementation It is highly recommended to use Parcelable implantation when serializing objects in android.

公共类User实现了Parcelable

点击这里查看更多信息

做谷歌命令你做的事!: http://developer.android.com/resources/faq/framework.html # 3

基本数据类型 非持久化对象 单例类-我最喜欢的:D 一个公共静态字段/方法 对象弱引用的HashMap 持久对象(应用程序首选项,文件,内容提供程序,SQLite DB)