Wednesday, 15 April 2020

How to pass object using intent in Android

This is the most frequently asked question in the Android interview, and here is the sample code to pass the object using intent in Android.
We can pass the object by making it as Serializable. Serializing an object means converting its state into a byte stream so that it can be read to get the object back. To make a class Serializable, the class needs to implement it with the Serializable interface.
Here is an example.

//Object class
public class Student implements Serializable {
private String name;
private String address;
private String dateOfBirth;
private long rollNumber;
}


//First Activity
Student student = new Student();
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("objdata", student);
startActivity(intent);


//Second Activity
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Student student = (Student) getIntent().getSerializableExtra()("objdata");
}
}

No comments:

Post a Comment