Better Way To Pass Data Between Activities In Android
Solution 1:
Implement the Parcelable
interface in your custom object and transmit it via an Intent
.
Here is an example of a Parcelable
object.
publicclassMyObjectimplementsParcelable {
privateStringsomeString=null;
privateintsomeInteger=0;
publicMyObject() {
// perform initialization if necessary
}
privateMyObject(Parcel in) {
someString = in.readString();
someInteger = in.readInt();
}
publicstaticfinal Parcelable.Creator<MyObject> CREATOR =
newParcelable.Creator<MyObject>() {
@Overridepublic MyObject createFromParcel(Parcel source) {
returnnewMyObject(source);
}
@Overridepublic MyObject[] newArray(int size) {
returnnewMyObject[size];
}
};
// Getters and setters@OverridepublicintdescribeContents() {
return0;
}
@OverridepublicvoidwriteToParcel(Parcel dest, int flags) {
dest.writeString(someString);
dest.writeInt(someInteger);
}
}
Here is what happens. If you implement the Parcelable
interface you have to create a private constructor which takes a Parcel
as a parameter. That Parcel
holds all the serialized values.
You must implement the nested class Parcelable.Creator
with the name CREATOR
as this is going to be called by Android when recreating your object.
The method describeContents()
is only of use in special cases. You can leave it as it is with a return value of 0
.
The interesting action happens in writeToParcel()
where you, as the name tells, write your data to a Parcel
object.
Now you can just add your custom object directly to an Intent
like in this example.
MyObjectmyObject=newMyObject();
Intenti=newIntent();
i.setExtra("MY_OBJECT", myObject);
// implicit or explicit destination declaration
startActivity(i);
Solution 2:
you can use Application class present in Android to pass data between activities.
here is a good link..http://www.helloandroid.com/tutorials/maintaining-global-application-state
Post a Comment for "Better Way To Pass Data Between Activities In Android"