How to pass object from ActivityA to ActivityB
In this code snippet am describing about how to pass class object from one activity to another activity. We all know that for passing messages from one activity to another we are using Intent. There is some methods available like putString(), putInt() and so on.
For this purpose we are using
java.io.Serializable
Please see the code below that will explains this in detail.
- Create your own class that implements from Serializable,
import import java.io.Serializable; public class Customer implements Serializable { private String name; private String city; public Customer() {} public Customer(String name, String city) { this.name = name; this.city = city; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } } - In ActivityA we need to call the ActivityB in a button click and add the following,
Customer cust=new Customer(); cust.setName("abc"); cust.setCity("xyz"); Intent intent=new Intent(abc.this,ActivityB.class); intent.putExtra("bundle",cust); startActivity(intent); - In ActivityB onCreate method we need to get these values by the following way:
Customer cust=(Customer)intent.getSerializableExtra("bundle"); textViewName.setText(cust.getName()); textViewCity.setText(cust.getCity());
Now the cust object will contains all the values.
