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

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

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

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


当前回答

在活动之间共享数据 使用实例登录后传递邮件

“email”是可以用来引用正在请求的活动的值的名称

1登录界面代码

Intent openLoginActivity = new Intent(getBaseContext(), Home.class);
    openLoginActivity.putExtra("email", getEmail);

主页上的2个代码

Bundle extras = getIntent().getExtras();
    accountEmail = extras.getString("email");

其他回答

你可以用什么:

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

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

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

如果你的意图是从当前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.

有一种新的更好的方式可以在活动之间共享数据,它就是LiveData。特别要注意Android开发者页面上的这句话:

LiveData对象能够感知生命周期这一事实意味着您可以在多个活动、片段和服务之间共享它们。为了保持示例简单,可以将LiveData类实现为单例

这样做的意义是巨大的——任何模型数据都可以在LiveData包装器中的公共单例类中共享。为了可测试性,它可以从活动中注入到各自的ViewModel中。并且您不再需要担心弱引用来防止内存泄漏。

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可以回收映射条目。