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

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

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

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


当前回答

你可以用什么:

在活动之间传递数据(如Cristian所说) 使用带有大量静态变量的类(这样就可以在不使用类实例和getter/setter的情况下调用它们) 使用数据库 共同的喜好

你选择什么取决于你的需要。当你使用"a lot of"时,你可能会使用不止一种方式

其他回答

“然而,我想分享很多 变量,有些可能是 很大,所以我不想创造 像上面这样的副本。”

这并不会产生复制(特别是对于String,但即使对象也是通过引用的值传递的,而不是对象本身,像这样的getter是可以使用的——可以说比其他方法更好使用,因为它们是常见的和易于理解的)。旧的“性能神话”,比如不使用getter和setter,仍然有一些价值,但也在文档中更新了。

但如果你不想那样做,你也可以让变量在GlobalState中为public或protected,然后直接访问它们。并且,你可以创建一个静态单例,就像Application对象JavaDoc指出的那样:

通常不需要子类化 应用程序。在大多数情况下, 静态单例也可以提供同样的功能 以更模块化的方式实现功能。 如果你的单例需要全局 上下文(例如注册 广播接收机),功能到 检索时可以给它一个Context 内部使用 Context.getApplicationContext()时 首先构造单例。

使用Intent数据是传递数据的另一种方式,但它通常用于较小的数据和简单类型。您可以传递更大/更复杂的数据,但这比使用静态单leon更复杂。不过,Application对象仍然是我个人最喜欢的在Android应用程序组件之间共享更大/更复杂的非持久性数据的对象(因为它在Android应用程序中有一个定义良好的生命周期)。

另外,正如其他人所注意到的,如果数据变得非常复杂并且需要持久化,那么您也可以使用SQLite或文件系统。

我有一些想法,但我不知道它们是否是你想要的。

您可以使用一个保存所有数据的服务,然后将活动绑定到该服务以进行数据检索。

或者将您的数据打包为可序列化或可打包的,并将它们附加到一个bundle中,并在活动之间传递该bundle。

这可能根本不是你要找的,但你也可以尝试使用SharedPreferences或一般的首选项。

不管怎样,让我知道你的决定。

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

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

点击这里查看更多信息

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

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

希望这是你想要的。

All of the aforementioned answers are great... I'm just adding one no one had mentioned yet about persisting data through activities and that is to use the built in android SQLite database to persist relevant data... In fact you can place your databaseHelper in the application state and call it as needed throughout the activates.. Or just make a helper class and make the DB calls when needed... Just adding another layer for you to consider... But all of the other answers would suffice as well.. Really just preference