Recipe 1.3 Passing Objects Between Activities
In the previous recipe, you saw how to pass simple data (such as strings and integers) between activities. This recipe demonstrates how to pass objects between activites. For example, you might have encapsulated the information of a customer (such as the customer ID, name, company, and so on) within an object and you need to pass it over to another activity for processing. Instead of passing the various pieces of the information of the customer individually, it would be easier to simply pass that object.
Solution
Besides passing simple data types using the putExtra() and putExtras() methods, you can also pass objects using an Intent object. If you have your own custom class, you need to ensure that your class implements the Serializable base class. The following MyCustomClass class is an example:
package net.learn2develop.passingdata;
import java.io.Serializable;
public class MyCustomClass implements Serializable {
private static final long serialVersionUID = 1L;
String _name;
String _email;
public void setName(String name) {
_name = name;
}
public String Name() {
return _name;
}
public void setEmail(String email) {
_email = email;
}
public String Email() {
return _email;
}
}
To pass an object to another activity, use the putExtra() method:
public void onClick(View view) { Intent i = new Intent("net.learn2develop.SecondActivity"); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access