How can I pass an object of a custom type from one Activity to another using the
putExtra()
method of the class Intent?
the most easiest solution i found is.. to create a class with static data members with getters setters.
set from one activity and get from another activity that object.
activity A
mytestclass.staticfunctionSet("","",""..etc.);
activity b
mytestclass obj= mytestclass.staticfunctionGet();
First implement Parcelable in your class. Then pass object like this.
SendActivity.java
ObjectA obj = new ObjectA();
// Set values etc.
Intent i = new Intent(this, MyActivity.class);
i.putExtra("com.package.ObjectA", obj);
startActivity(i);
ReceiveActivity.java
Bundle b = getIntent().getExtras();
ObjectA obj = b.getParcelable("com.package.ObjectA");
The package string isn't necessary, just the string needs to be the same in both Activities
REFERENCE
if your object class implements Serializable
, you don't need to do anything else, you can pass a serializable object.
that's what i use.
implement serializable in your class
public class Place implements Serializable{
private int id;
private String name;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Then you can pass this object in intent
Intent intent = new Intent(this, SecondAct.class);
intent.putExtra("PLACE", Place);
startActivity(intent);
int the second activity you can get data like this
Place place= (Place) getIntent().getSerializableExtra("PLACE");
But when the data become large,this method will be slow.
I know this is late but it is very simple.All you have do is let your class implement Serializable like
public class MyClass implements Serializable{
}
then you can pass to an intent like
Intent intent=......
MyClass obje=new MyClass();
intent.putExtra("someStringHere",obje);
To get it you simpley call
MyClass objec=(MyClass)intent.getExtra("theString");
If you are not very particular about using the putExtra feature and just want to launch another activity with objects, you can check out the GNLauncher (https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher) library I wrote in an attempt to make this process more straight forward.
GNLauncher makes sending objects/data to an Activity from another Activity etc as easy as calling a function in the Activity with the required data as parameters. It introduces type safety and removes all the hassles of having to serialize, attaching to the intent using string keys and undoing the same at the other end.