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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2736389/
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-13 12:17:56  来源:igfitidea点击:

How to pass an object from one activity to another on Android

javaandroidobjectandroid-intentandroid-activity

提问by kaibuki

I am trying to work on sending an object of my customerclass from one Activityand display it in another Activity.

我正在尝试从一个对象发送我的客户类的对象Activity并将其显示在另一个Activity.

The code for the customer class:

客户类的代码:

public class Customer {

    private String firstName, lastName, Address;
    int Age;

    public Customer(String fname, String lname, int age, String address) {

        firstName = fname;
        lastName = lname;
        Age = age;
        Address = address;
    }

    public String printValues() {

        String data = null;

        data = "First Name :" + firstName + " Last Name :" + lastName
        + " Age : " + Age + " Address : " + Address;

        return data;
    }
}

I want to send its object from one Activityto another and then display the data on the other Activity.

我想将它的对象从一个发送Activity到另一个,然后在另一个上显示数据Activity

How can I achieve that?

我怎样才能做到这一点?

采纳答案by Samuh

One option could be letting your custom class implement the Serializableinterface and then you can pass object instances in the intent extra using the putExtra(Serializable..)variant of the Intent#putExtra()method.

一种选择是让您的自定义类实现Serializable接口,然后您可以使用方法的putExtra(Serializable..)变体在 Intent extra 中传递对象实例Intent#putExtra()

Pseudocode:

伪代码

//To pass:
intent.putExtra("MyClass", obj);

// To retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");

Note: Make sure each nested class of your main custom class has implemented Serializable interface to avoid any serialization exceptions. For example:

注意:确保主自定义类的每个嵌套类都实现了 Serializable 接口以避免任何序列化异常。例如:

class MainClass implements Serializable {

    public MainClass() {}

    public static class ChildClass implements Serializable {

        public ChildClass() {}
    }
}

回答by Vidar Vestnes

If you choose use the way Samuh describes, remember that only primitive values can be sent. That is, values that are parcable. So, if your object contains complex objects these will not follow. For example, variables like Bitmap, HashMap etc... These are tricky to pass by the intent.

如果您选择使用 Samuh 描述的方式,请记住只能发送原始值。也就是说,可解释的值。因此,如果您的对象包含复杂的对象,这些将不会跟随。例如,像 Bitmap、HashMap 等变量......这些很难通过意图传递。

In general I would advice you to send only primitive datatypes as extras, like String, int, boolean etc. In your case it would be: String fname, String lname, int age, and String address.

一般来说,我会建议你发送基本数据类型的演员,如String,整型,布尔等。在你的情况将是:String fnameString lnameint age,和String address

My opinion: More complex objects are better shared by implementing a ContentProvider, SDCard, etc. It's also possible to use a static variable, but this may fastly lead to error-prone code...

我的意见:通过实现ContentProviderSDCard等更好地共享更复杂的对象。也可以使用静态变量,但这可能很快导致容易出错的代码......

But again, it's just my subjective opinion.

但同样,这只是我的主观意见。

回答by MJB

You could also write the object's data into temporary Strings and ints, and pass them to the activity. Of course that way, you get the data transported, but not the object itself.

您还可以将对象的数据写入临时字符串和整数,并将它们传递给活动。当然,通过这种方式,您可以传输数据,而不是对象本身。

But if you just want to display them, and not use the object in another method or something like that, it should be enough. I did it the same way to just display data from one object in another activity.

但是如果你只是想显示它们,而不是在另一个方法或类似的东西中使用对象,那就足够了。我以同样的方式在另一个活动中显示来自一个对象的数据。

String fName_temp   = yourObject.getFname();
String lName_temp   = yourObject.getLname();
String age_temp     = yourObject.getAge();
String address_temp = yourObject.getAddress();

Intent i = new Intent(this, ToClass.class);
i.putExtra("fname", fName_temp);
i.putExtra("lname", lName_temp);
i.putExtra("age", age_temp);
i.putExtra("address", address_temp);

startActivity(i);

You could also pass them in directly instead of the temp ivars, but this way it's clearer, in my opinion. Additionally, you can set the temp ivars to null so that they get cleaned by the GarbageCollector sooner.

你也可以直接传递它们而不是临时变量,但在我看来,这样更清晰。此外,您可以将临时变量设置为 null,以便 GarbageCollector 更快地清除它们。

Good luck!

祝你好运!

On a side note: override toString() instead of writing your own print method.

附带说明:覆盖 toString() 而不是编写自己的打印方法。

As mentioned in the comments below, this is how you get your data back in another activity:

正如下面的评论中所提到的,这是您在另一个活动中取回数据的方式:

String fName = getIntent().getExtras().getInt("fname");

回答by Umesh

The best way is to have a class (call it Control) in your application that will hold a static variable of type 'Customer' (in your case). Initialize the variable in your Activity A.

最好的方法是在您的应用程序中有一个类(称为 Control),该类将保存一个类型为“Customer”的静态变量(在您的情况下)。初始化活动 A 中的变量。

For example:

例如:

Control.Customer = CustomerClass;

Then go to Activity B and fetch it from Control class. Don't forget to assign a null after using the variable, otherwise memory will be wasted.

然后转到 Activity B 并从 Control 类中获取它。使用完变量后不要忘记赋值为null,否则会浪费内存。

回答by alistair

Yeah, using a static object is by far the easiest way of doing this with custom non-serialisable objects.

是的,使用静态对象是迄今为止使用自定义不可序列化对象执行此操作的最简单方法。

回答by Ads

While calling an activity

在调用活动时

Intent intent = new Intent(fromClass.this,toClass.class).putExtra("myCustomerObj",customerObj);

In toClass.java receive the activity by

在 toClass.java 中通过以下方式接收活动

Customer customerObjInToClass = getIntent().getExtras().getParcelable("myCustomerObj");

Please make sure that customer class implements parcelable

请确保客户类实现了parcelable

public class Customer implements Parcelable {

    private String firstName, lastName, address;
    int age;

    /* all your getter and setter methods */

    public Customer(Parcel in ) {
        readFromParcel( in );
    }

    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        public LeadData createFromParcel(Parcel in ) {
            return new Customer( in );
        }

        public Customer[] newArray(int size) {
            return new Customer[size];
        }
    };


    @Override
    public void writeToParcel(Parcel dest, int flags) {

        dest.writeString(firstName);
        dest.writeString(lastName);
        dest.writeString(address);
        dest.writeInt(age);
    }

    private void readFromParcel(Parcel in ) {

        firstName = in .readString();
        lastName  = in .readString();
        address   = in .readString();
        age       = in .readInt();
    }

回答by Dennso

As mentioned in the comments, this answer breaks encapsulation and tightly couplescomponents, which is very likely not what you want. The best solution is probably making your object Parcelable or Serializable, as other responses explain. Having said that, the solution solves the problem. So if you know what you are doing:

正如评论中提到的,这个答案打破了封装并紧密耦合了组件,这很可能不是你想要的。最好的解决方案可能是使您的对象 Parcelable 或 Serializable,正如其他回复所解释的那样。话虽如此,解决方案解决了问题。因此,如果您知道自己在做什么:

Use a class with static fields:

使用带有静态字段的类:

public class Globals {
    public static Customer customer = new Customer();
}

Inside the activities you can use:

在您可以使用的活动中:

Activity From:

活动自:

Globals.customer = myCustomerFromActivity;

Activity Target:

活动目标:

myCustomerTo = Globals.customer;

It's an easy way to pass information for activities.

这是一种为活动传递信息的简单方法。

回答by Barbariska

You can try to use that class. The limitation is that it can't be used outside of one process.

您可以尝试使用该类。限制是它不能在一个进程之外使用。

One activity:

一项活动:

 final Object obj1 = new Object();
 final Intent in = new Intent();
 in.putExtra(EXTRA_TEST, new Sharable(obj1));

Other activity:

其他活动:

final Sharable s = in.getExtras().getParcelable(EXTRA_TEST);
final Object obj2 = s.obj();

public final class Sharable implements Parcelable {

    private Object mObject;

    public static final Parcelable.Creator < Sharable > CREATOR = new Parcelable.Creator < Sharable > () {
        public Sharable createFromParcel(Parcel in ) {
            return new Sharable( in );
        }


        @Override
        public Sharable[] newArray(int size) {
            return new Sharable[size];
        }
    };

    public Sharable(final Object obj) {
        mObject = obj;
    }

    public Sharable(Parcel in ) {
        readFromParcel( in );
    }

    Object obj() {
        return mObject;
    }


    @Override
    public int describeContents() {
        return 0;
    }


    @Override
    public void writeToParcel(final Parcel out, int flags) {
        final long val = SystemClock.elapsedRealtime();
        out.writeLong(val);
        put(val, mObject);
    }

    private void readFromParcel(final Parcel in ) {
        final long val = in .readLong();
        mObject = get(val);
    }

    /////

    private static final HashMap < Long, Object > sSharableMap = new HashMap < Long, Object > (3);

    synchronized private static void put(long key, final Object obj) {
        sSharableMap.put(key, obj);
    }

    synchronized private static Object get(long key) {
        return sSharableMap.remove(key);
    }
}

回答by Mustafa Güven

Implement your class with Serializable. Let's suppose that this is your entity class:

使用 Serializable 实现您的类。假设这是您的实体类:

import java.io.Serializable;

@SuppressWarnings("serial") //With this annotation we are going to hide compiler warnings
public class Deneme implements Serializable {

    public Deneme(double id, String name) {
        this.id = id;
        this.name = name;
    }

    public double getId() {
        return id;
    }

    public void setId(double id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private double id;
    private String name;
}

We are sending the object called denefrom X activity to Y activity. Somewhere in X activity;

我们dene将从 X 活动调用的对象发送到 Y 活动。X 活动中的某个地方;

Deneme dene = new Deneme(4,"Mustafa");
Intent i = new Intent(this, Y.class);
i.putExtra("sampleObject", dene);
startActivity(i);

In Y activity we are getting the object.

在 Y 活动中,我们正在获取对象。

Intent i = getIntent();
Deneme dene = (Deneme)i.getSerializableExtra("sampleObject");

That's it.

就是这样。

回答by Dhiral Pandya

public class MyClass implements Serializable{
    Here is your instance variable
}

Now you want to pass the object of this class in startActivity. Simply use this:

现在你想在 startActivity 中传递这个类的对象。只需使用这个:

Bundle b = new Bundle();
b.putSerializable("name", myClassObject);
intent.putExtras(b);

This works here because MyClass implements Serializable.

这在这里有效是因为 MyClass 实现了Serializable.