Reputation: 8425
In my application I am fetching data from JavaScript, as it is not possible to return the data as an array or object, I am returning it as a String.
Now to organize the data I am creating a class which contains ArrayList
s and other string variables and further I am creating array of my class objects variable to store multiple records.
public class Data {
ArrayList<String> m_empArrayList = new ArrayList();
ArrayList<String> m_depArrayList = new ArrayList();
String m_time;
String m_duration;
}
Data d = new Data();
What would be a good approach to pass the data between Activities? As Intent
s and ShredPrefrence
s are used to pass small units of data I am not considering it here.
Upvotes: 2
Views: 3420
Reputation: 39604
Implement the Parcelable
interface in your custom object and transmit it via an Intent
.
Here is an example of a Parcelable
object.
public class MyObject implements Parcelable {
private String someString = null;
private int someInteger = 0;
public MyObject() {
// perform initialization if necessary
}
private MyObject(Parcel in) {
someString = in.readString();
someInteger = in.readInt();
}
public static final Parcelable.Creator<MyObject> CREATOR =
new Parcelable.Creator<MyObject>() {
@Override
public MyObject createFromParcel(Parcel source) {
return new MyObject(source);
}
@Override
public MyObject[] newArray(int size) {
return new MyObject[size];
}
};
// Getters and setters
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(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.
MyObject myObject = new MyObject();
Intent i = new Intent();
i.setExtra("MY_OBJECT", myObject);
// implicit or explicit destination declaration
startActivity(i);
Upvotes: 6
Reputation: 10622
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
Upvotes: 3