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

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

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

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


当前回答

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

其他回答

在活动之间共享数据有多种方式

1:使用Intent在活动之间传递数据

Intent intent=new Intent(this, desirableActivity.class);
intent.putExtra("KEY", "Value");
startActivity(intent)

2:使用静态关键字,将变量定义为公共静态,并在项目中使用任何位置

      public static int sInitialValue=0;

在项目的任何地方使用classname.variableName;

3:使用数据库

但其过程较长,插入数据时必须使用查询,需要时使用游标迭代数据。但是如果不清理缓存就不会丢失数据。

4:使用共享首选项

比数据库简单多了。但是有一些限制,你不能保存ArrayList,List和自定义对象。

5:在application类中创建getter setter,并访问项目中的任何地方。

      private String data;
      public String getData() {
          return data;
      }

      public void setData(String data) {
          this.data = data;
      }

这里设置和获取活动

         ((YourApplicationClass)getApplicationContext()).setData("abc"); 

         String data=((YourApplicationClass)getApplicationContext()).getData();  

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

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

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

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

希望这是你想要的。

你可以用什么:

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

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