如何在 Android 上将对象从一个活动传递到另一个活动?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2906925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:49:49  来源:igfitidea点击:

How do I pass an object from one activity to another on Android?

androidobjectandroid-activity

提问by mtmurdock

I need to be able to use one object in multiple activities within my app, and it needs to be the sameobject. What is the best way to do this?

我需要能够在我的应用程序中的多个活动中使用一个对象,并且它需要是同一个对象。做这个的最好方式是什么?

I have tried making the object "public static" so it can be accessed by other activities, but for some reason this just isn't cutting it. Is there another way of doing this?

我曾尝试将对象设为“公共静态”,以便其他活动可以访问它,但出于某种原因,这并没有削减它。还有另一种方法吗?

回答by anargund

When you are creating an object of intent, you can take advantage of following two methods for passing objects between two activities.

创建意向对象时,可以利用以下两种方法在两个活动之间传递对象。

putParcelable

putParcelable

putSerializable

可序列化

You can have your class implement either Parcelableor Serializable. Then you can pass around your custom classes across activities. I have found this very useful.

您可以让您的类实现ParcelableSerializable。然后,您可以跨活动传递自定义类。我发现这非常有用。

Here is a small snippet of code I am using

这是我正在使用的一小段代码

CustomListing currentListing = new CustomListing();
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable(Constants.CUSTOM_LISTING, currentListing);
i.putExtras(b);
i.setClass(this, SearchDetailsActivity.class);
startActivity(i);

And in newly started activity code will be something like this...

在新启动的活动代码中将是这样的......

Bundle b = this.getIntent().getExtras();
if (b != null)
    mCurrentListing = b.getParcelable(Constants.CUSTOM_LISTING);

回答by Erich Douglass

You can create a subclass of Applicationand store your shared object there. The Application object should exist for the lifetime of your app as long as there is some active component.

您可以创建Application的子类并将共享对象存储在那里。只要有一些活动组件,Application 对象就应该在您的应用程序的生命周期内存在。

From your activities, you can access the application object via getApplication().

从您的活动中,您可以通过getApplication().

回答by Subin Sebastian

This answer is specific to situations where the objects to be passed has nested class structure. With nested class structure, making it Parcelable or Serializeable is a bit tedious. And, the process of serialising an object is not efficient on Android. Consider the example below,

此答案特定于要传递的对象具有嵌套类结构的情况。使用嵌套的类结构,让它 Parcelable 或 Serializeable 有点乏味。而且,序列化对象的过程在 Android 上效率不高。考虑下面的例子,

class Myclass    {
  int a;
  class SubClass    {
       int b;
  }
}

With Google's GSON library, you can directly parse an object into a JSON formatted String and convert it back to the object format after usage. For example,

借助谷歌的GSON 库,您可以直接将对象解析为 JSON 格式的 String,并在使用后将其转换回对象格式。例如,

MyClass src = new MyClass();
Gson gS = new Gson();
String target = gS.toJson(src); // Converts the object to a JSON String

Now you can pass this String across activities as a StringExtra with the activity intent.

现在,您可以将此字符串作为具有活动意图的 StringExtra 跨活动传递。

Intent i = new Intent(FromActivity.this, ToActivity.class);
i.putExtra("MyObjectAsString", target);

Then in the receiving activity, create the original object from the string representation.

然后在接收活动中,根据字符串表示创建原始对象。

String target = getIntent().getStringExtra("MyObjectAsString");
MyClass src = gS.fromJson(target, MyClass.class); // Converts the JSON String to an Object

It keeps the original classes clean and reusable. Above of all, if these class objects are created from the web as JSON objects, then this solution is very efficient and time saving.

它使原始类保持清洁和可重用。最重要的是,如果这些类对象是作为 JSON 对象从网络创建的,那么该解决方案非常高效且节省时间。

UPDATE

更新



While the above explained method works for most situations, for obvious performance reasons, do not rely on Android's bundled-extra system to pass objects around. There are a number of solutions makes this process flexible and efficient, here are a few. Each has its own pros and cons.

虽然上面解释的方法适用于大多数情况,但出于明显的性能原因,不要依赖 Android 的 bundled-extra 系统来传递对象。有许多解决方案可以使这个过程灵活高效,这里有一些。每个都有自己的优点和缺点。

  1. Eventbus
  2. Otto
  1. 事件总线
  2. 奥托

回答by Chris Stewart

Maybe it's an unpopular answer, but in the past I've simply used a class that has a static reference to the object I want to persist through activities. So,

也许这是一个不受欢迎的答案,但在过去,我只是使用了一个类,该类具有对我想要通过活动持久化的对象的静态引用。所以,

public class PersonHelper
{
    public static Person person;
}

I tried going down the Parcelable interface path, but ran into a number of issues with it and the overhead in your code was unappealing to me.

我尝试使用 Parcelable 接口路径,但遇到了许多问题,并且您的代码中的开销对我没有吸引力。

回答by CaseyB

It depends on the type of data you need access to. If you have some kind of data pool that needs to persist across Activitys then Erich's answer is the way to go. If you just need to pass a few objects from one activity to another then you can have them implement Serializableand pass them in the extras of the Intentto start the new Activity.

这取决于您需要访问的数据类型。如果您有某种需要跨Activitys持久化的数据池,那么 Erich 的答案就是要走的路。如果您只需要将一些对象从一个活动传递到另一个活动,那么您可以让它们实现Serializable并将它们传递到 的 extra 中Intent以启动新的Activity.

回答by Fedor

Your object can also implement the Parcelable interface. Then you can use the Bundle.putParcelable()method and pass your object between activities within intent.

您的对象还可以实现 Parcelable 接口。然后您可以使用该Bundle.putParcelable()方法并在意图内的活动之间传递您的对象。

The Photostreamapplication uses this approach and may be used as a reference.

照片流应用程序使用此方法,并且可以被用作参考。