Returning object from child activity in android
I have a main_activity that launches a child Activity
via Intent
.
I am aware of the methods getStringExtra(string)
or getBooleanExtra(string)
etc that we call in onActivityResult
; But they are all return
primitive data ... How can I get an object from a custom class from a child activity?
Thanks, and this is my first question! :) seems to be too late ...
source to share
You are looking for Parcelable
.
A simpler, though not optimal solution Serializable
.
Excerpt:
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
Using:
// Sender class
MyParcelable mp = new MyParcelable();
intent.putExtra("KEY_PARCEL", mp);
// Receiver class
Bundle data = getIntent().getExtras();
MyParcelable student = (Myparcelable)data.getParcelable("KEY_PARCEL");
EDIT : Here's how to do it with fragments.
// Receiver class
Bundle data = getIntent().getExtras();
public class MyFragment extends Fragment {
public static MyFragment newInstance(int index, Bundle data) {
MyFragment f = new MyFragment();
data.putInt("index", index);
f.setArguments(data);
return f;
}
}
// In the fragment
Bundle data = getArguments();
source to share
There is this site that makes Parselabel classes from your custom class .... swweeeeeet! http://www.parcelabler.com/
source to share