snippetjavaCritical
How to pass an object from one activity to another on Android
Viewed 0 times
objecthowfromandroidactivityoneanotherpass
Problem
I am trying to work on sending an object of my customer class from one
The code for the customer class:
I want to send its object from one
How can I achieve that?
Activity and displaying it in another Activity.The code for the customer class:
public class Customer {
private String firstName, lastName, address;
int age;
public Customer(String fname, String lname, int age, String address) {
firstName = fname;
lastName = lname;
age = age;
address = address;
}
public String printValues() {
String data = null;
data = "First Name :" + firstName + " Last Name :" + lastName
+ " Age : " + age + " Address : " + address;
return data;
}
}I want to send its object from one
Activity to another and then display the data on the other Activity.How can I achieve that?
Solution
One option could be letting your custom class implement the
Actual Code:
In Your Custom Model/Object Class:
At other class where using the Custom Model/Class:
myObject is of type "YourClass".
Then to retrieve from another activity, use getSerializableExtra
get the object using same Key name. And typecast to YourClass is needed:
Note: Make sure each nested class of your main custom class has implemented Serializable interface to avoid any serialization exceptions. For example:
Serializable interface and then you can pass object instances in the intent extra using the putExtra(Serializable..) variant of the Intent#putExtra() method.Actual Code:
In Your Custom Model/Object Class:
public class YourClass implements Serializable {At other class where using the Custom Model/Class:
//To pass:
intent.putExtra("KEY_NAME", myObject);myObject is of type "YourClass".
Then to retrieve from another activity, use getSerializableExtra
get the object using same Key name. And typecast to YourClass is needed:
// To retrieve object in second Activity
myObject = (YourClass) getIntent().getSerializableExtra("KEY_NAME");Note: Make sure each nested class of your main custom class has implemented Serializable interface to avoid any serialization exceptions. For example:
class MainClass implements Serializable {
public MainClass() {}
public static class ChildClass implements Serializable {
public ChildClass() {}
}
}Code Snippets
public class YourClass implements Serializable {//To pass:
intent.putExtra("KEY_NAME", myObject);// To retrieve object in second Activity
myObject = (YourClass) getIntent().getSerializableExtra("KEY_NAME");class MainClass implements Serializable {
public MainClass() {}
public static class ChildClass implements Serializable {
public ChildClass() {}
}
}Context
Stack Overflow Q#2736389, score: 979
Revisions (0)
No revisions yet.