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

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

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

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


当前回答

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

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

点击这里查看更多信息

其他回答

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

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

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

点击这里查看更多信息

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

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

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

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

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

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

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

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

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

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();