How can I pass an object of a custom type from one Activity to another using the
putExtra()
method of the class Intent?
Start another activity from this activity pass parameters via Bundle Object
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);
Retrieve on another activity (YourActivity)
String s = getIntent().getStringExtra("USER_NAME");
This is ok for simple kind data type. But if u want to pass complex data in between activity u need to serialize it first.
Here we have Employee Model
class Employee{
private String empId;
private int age;
print Double salary;
getters...
setters...
}
You can use Gson lib provided by google to serialize the complex data like this
String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);
startActivity(intent);
Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
Gson gson = new Gson();
Type type = new TypeToken() {
}.getType();
Employee selectedEmp = gson.fromJson(empStr, type);