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

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

问题描述:

我正在尝试从一个 Activity 发送我的 customer 类的对象,并在另一个 Activity 中显示它.

I am trying to work on sending an object of my customer class from one Activity and display it in another Activity.

客户类的代码:

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;
    }
}

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

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

我怎样才能做到这一点?

How can I achieve that?

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

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

伪代码:

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

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

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

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

class MainClass implements Serializable {

    public MainClass() {}

    public static class ChildClass implements Serializable {

        public ChildClass() {}
    }
}