Reputation: 5955
I have read almost topics here how to pass a complex object to an activity. There are two ways to do:
1) Serializable object
2) Parcelable object
All the examples I saw are still simple objects or objects that contains primitive fields, or these fields can be serializable or parcelable.Now, let suppose I have a really really complex object such as:
public class ComplexObject{ private Class1 object1; private Class2 object2; .... private ClassN objectN; }
The ith object can contain non-primitive fields. Now if I want to pass the ComplexObject to an activity, I have to serialize or parcelize every fields Class1, Class2, ClassN. Is there anyway to still pass my ComplexObject without doing every serialize or parcelize?
Upvotes: 0
Views: 186
Reputation: 22232
If your complexObject is an application model, I suggest putting it in Application
subclass, where it can be accessed from any component (Activity
, Service
). If you have more objects, put them in a List
or Map
inside model and pass identifier between Activities
.
No need to make everything Parcelable
.
Upvotes: 2
Reputation: 6563
You can do it though Parcelable
public class MyParcelable implements Parcelable {
private Class1 object1;
private Class2 object2;
....
private ClassN objectN;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeParcelable(object1, flags)
out.writeParcelable(object2, flags)
...
out.writeParcelable(objectN, flags)
}
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) {
object1 = in.readParcelable(Class1.class.getClassLoader());
object2 = in.readParcelable(Class2.class.getClassLoader());
...
objectN = in.readParcelable(ClassN.class.getClassLoader());
}
}
I assume that Class1
, Class2
, ..., ClassN
are already implemented Parcelable
.
Upvotes: 1
Reputation: 46846
no, your top level object must be either serializeable, or parecelable in order to pass it as an Extra, and for that to work any child objects must also be serializable or parcelable.
These interfaces are the only way that the system knows how to package your data. Without implementing them it would have no way to know how to "break down" an arbitrary object into primitives that can be passed along as an Extra.
Upvotes: 2