Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

java - 如何在Android上将对象从一项活动传递到另一项活动(How to pass an object from one activity to another on Android)

I am trying to work on sending an object of my customer class from one Activity and 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 Activity to another and then display the data on the other Activity .

(我想将其对象从一个Activity发送到另一个,然后在另一个Activity上显示数据。)

How can I achieve that?

(我该如何实现?)

  ask by kaibuki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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.

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

For example:

(例如:)

class MainClass implements Serializable {

    public MainClass() {}

    public static class ChildClass implements Serializable {

        public ChildClass() {}
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...