Passing data between activities is quite easy. You would normally do that using the Bundle packed into an intent. But sometimes you need to pass complex objects from one activity to another. One workaround would be to keep a static instance of the object int your Activity and access it from you new Activity. This might help, but it's definitely not a good way to do this. To pass such objects directly through the Bundle, your class would need to implement the Parcelable interface.
For example you have a class called Student, which has three fields.
1. id
2. name
3. grade
You can create a POJO class for this, but you need to add some extra code to make it Parcelable. Have a look at the implementation.
1: public class Student implements Parcelable{
2: private String id;
3: private String name;
4: private String grade;
5:
6: // Constructor
7: public Student(String id, String name, String grade){
8: this.id = id;
9: this.name = name;
10: this.grade = grade;
11: }
12: // Getter and setter methods
13: .........
14: .........
15:
16: // Parcelling part
17: public Student(Parcel in){
18: String[] data = new String[3];
19:
20: in.readStringArray(data);
21: this.id = data[0];
22: this.name = data[1];
23: this.grade = data[2];
24: }
25:
26: @override
27: public int describeContents(){
28: return 0;
29: }
30:
31: @Override
32: public void writeToParcel(Parcel dest, int flags) {
33: dest.writeStringArray(new String[] {this.id,
34: this.name,
35: this.grade});
36: }
37: public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
38: public Student createFromParcel(Parcel in) {
39: return new Student(in);
40: }
41:
42: public Student[] newArray(int size) {
43: return new Student[size];
44: }
45: };
46: }
Once you have created this class, you can easily pass objects of this class through the Intent like this, and recover this object in the target activity.
1: intent.putExtra("student", new Student("1","Mike","6"));
Here, the student is the key which you would require to unparcel the data from the bundle.
1: Bundle data = getIntent().getExtras();
2: Student student = data.getParcelable("student");
This example shows only String types. But, you can parcel any kind of data you want. Try it
@font-face { font-family: Wingdings; } @font-face { font-family: Cambria Math; } @font-face { font-family: Calibri; } @page Section1 {size: 8.5in 11.0in; margin: 1.0in 1.0in 1.0in 1.0in; mso-header-margin: .5in; mso-footer-margin: .5in; mso-paper-source: 0; } P.MsoNormal { LINE-HEIGHT: 115%; MARGIN: 0in 0in 10pt; FONT-FAMILY: "Calibri","sans-serif"; FONT-SIZE: 11pt; mso-style-unhide: no; mso-style-qformat: yes; mso-style-parent: ""; mso-pagination: widow-orphan; mso-fareast-font-family: Calibri; mso-bidi-font-family: "Times New Roman" } LI.MsoNormal { LINE-HEIGHT: 115%; MARGIN: 0in 0in 10pt; FONT-FAMILY: "Calibri","sans-serif"; FONT-SIZE: 11pt; mso-style-unhide: no; mso-style-qformat: yes; mso-style-parent: ""; mso-pagination: widow-orphan; mso-fareast-font-family: Calibri; mso-bidi-font-family: "Times New Roman" } DIV.MsoNormal { LINE-HEIGHT: 115%; MARGIN: 0in 0in 10pt; FONT-FAMILY: "Calibri","sans-serif"; FONT-SIZE: 11pt; mso-style-unhide: no; mso-style-qformat: yes; mso-style-parent: ""; mso-pagination: widow-orphan; mso-fareast-font-family: Calibri; mso-bidi-font-family: "Times New Roman" } .MsoChpDefault { FONT-SIZE: 10pt; mso-fareast-font-family: Calibri; mso-style-type: export-only; mso-default-props: yes; mso-ansi-font-size: 10.0pt; mso-bidi-font-size: 10.0pt; mso-ascii-font-family: Calibri; mso-hansi-font-family: Calibri } DIV.Section1 { page: Section1 }
Few days back I had a requirement to send ArrayList of my Custom Class/Objects which need to be sent through Intent, I guessmost of you also find this requirement now and then. I never thought it can be that tricky.
There are built in functions in Intent to send ArrayList of primitive objects e.g. String, Integer, but when it comes to Custom Data Handling Objects, BOOM… you need to take that extra pain…..
Android has defined a new light weight IPC (Inter Process Communication) data structure called Parcel, where you can flatten your objects in byte stream, same as J2SDK’s Serialization concept.
So let’s come back to my original requirement, I had a Data Handling class, which groups together a set of information-
public class ParcelData {
int id;
String name;
String desc;
String[] cities = {"suwon", "delhi"};
}
I want an ArrayList<
ParcelData> of Data Handling objects to be able to pass through Intent. To do that, I can’t use the
ParcelData as it is; you need to implement an Interface
android.os.Parcelable which will make Objects of this class Parcelable. So you need to define your data handling class as-
public class ParcelData implements Parcelable {
int id;
String name;
String desc;
String[] cities = {"suwon", "delhi"};
}
You need to overwrite2 methods of
android.os.Parcelable Interface-
describeContents()- define the kind of object you are going to Parcel, you can use the hashCode() here.
writeToParcel(Parcel dest, int flags)- actual object serialization/flattening happens here. You need to individually Parcel each element of the object.
public void writeToParcel(Parcel dest,
int flags) {
Log.
v(TAG, "writeToParcel..."+ flags);
dest.writeInt(id);
dest.writeString(name);
dest.writeString(desc);
dest.writeStringArray(cities);
}
Note: Don’t try things like, dest.writeValue(this) to flatten the complete Object at a time (I don’t think all people have some weird imaginations like me, so you’ll never try this, right ?…) that will end up in recursive call ofwriteToParcel().
Up to this point you are done with the required steps to flatten/serialize your custom object.
Next, you need to add steps to un-marshal/un-flatten/de-serialize
(whatever you call it) your custom data objects from Parcel. You need to define one weird variable called
CREATOR
of type Parcelable.Creator. If you don’t do that, Android framework will through exception-
Parcelable protocol requires a Parcelable.Creator object called CREATOR
Following is a sample implementation of Parcelable.Creator<
ParcelData> interface for my class
ParcelData.java-
/**
* It will be required during un-marshaling data stored in a Parcel
*
@author prasanta
*/
public class MyCreator implements Parcelable.Creator<
ParcelData> {
public ParcelData createFromParcel(Parcel source) {
return new ParcelData(source);
}
public ParcelData[] newArray(
int size) {
return new ParcelData[size];
}
}
You need to define a Constructor in
ParcelData.java which puts together all parceled data back-
/**
* This will be used only by the MyCreator
*
@param source
*/
public ParcelData(Parcel source){
/*
* Reconstruct from the Parcel
*/
Log.
v(TAG, "ParcelData(Parcel source): time to put back parcel data");
id = source.readInt();
name = source.readString();
desc = source.readString();
source.readStringArray(cities);
}
You can deserve some rest now…...as you are done with it. So now you can use, something like-
Intent parcelIntent =
new Intent(
this, ParcelActivity.
class);
ArrayList<
ParcelData> dataList =
new ArrayList<
ParcelData>();
/*
* Add elements in dataLists e.g.
* ParcelData pd1 = new ParcelData();
* ParcelData pd2 = new ParcelData();
*
* fill in data in pd1 and pd2
*
* dataLists.add(pd1);
* dataLists.add(pd2);
*/
parcelIntent.putParcelableArrayListExtra("custom_data_list", data);
So, how hard is that?