简体   繁体   中英

passing objects from one activity to another one

我正在Android Studio中的Android应用程序上工作,我知道如何使用Intent传递对象,但我想知道是否也可以使用getter和setter将对象从一个活动传递到另一个活动,以及是否有可能?

You can pass a base type of object as:

Activity 1?

Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);

intent.putExtra("data", somedata);

startActivity(intent );

And at the Activity 2:

Intent intent = getIntent();

String data = intent.getStringExtra("data");

If you wanna pass one object, this one should implements Serializable.

To pass:

intent.putExtra("MyClass", obj);

To retrieve object in second Activity

getIntent().getSerializableExtra("MyClass");

您绝对应该使用Intent通过Serializable或Parcelable传递对象。

please have a look on this code, you need to use like this:

public class Student implements Serializable
{


    private static final long serialVersionUID = 1L;
    int rollno;
    String name;

    public int getRollno() {
        return rollno;
    }
    public void setRollno(int rollno) {
        this.rollno = rollno;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

Now To pass the object of Student class From Activity 'A' to activity 'B':

Student stud = new Student();
Intent aActivity = (A.this, B.class);
intent.putExtra("StudentObject", stud);

To retrieve object in second Activity ie in 'B' activity, write the below line:

Student studObject = getIntent().getSerializableExtra("StudentObject");

You cannot use getters and setters to pass an object to the NextActivity but this is possible if you intend to marshal the object and pass just the Components of the object one by one like String, int etc from the object to the NextActivity and this is not recommended except you want to get one or few components from the object.

The implications of breaking an object into pieces manually and putting each as an extra to intent is it consumes more resources and makes transition to the NextActivity slow. In order to avoid this kind of scenario, Android Parcelable and Java Serializable is introduced.

For information on Parcellable, visit https://developer.android.com/reference/android/os/Parcelable and on Serializable https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM