Write an extra Parcelable class for another section

I have a class that implements the Parcelable interface:

 class A implements Parcelable { } 

I have another class B that contains object A as an instance variable. In writeToPacel inside class B I want to write object B to Parcel :

 class B implements Parcelable{ public void writeToParcel(Parcel dest, int flags) { dest.write ??? } } 

How can I write and read?

+49
android parcelable
Sep 02 '12 at 20:05
source share
3 answers
 class B implements Parcelable{ //lets assume you have A as a data member A obj; public void writeToParcel(Parcel dest, int flags) { dest.writeParcelable(obj , flags); } } 

if you want to read it use this

  obj = in.readParcelable(A.class.getClassLoader()); 
+142
Sep 02 '12 at 20:37
source share

The best way to handle this, which avoids reflection, is to simply call the static creator in the target type as follows:

 this.amazingObject = AmazingObject.CREATOR.createFromParcel(in); 

and write it to Parcelable using this.amazingObject.writeToParcel(Parcel, int)

Internally, when calling readParcelable(ClassLoader) this happens:

 public final <T extends Parcelable> T readParcelable(ClassLoader loader) { Parcelable.Creator<T> creator = readParcelableCreator(loader); if (creator == null) { return null; } if (creator instanceof Parcelable.ClassLoaderCreator<?>) { return ((Parcelable.ClassLoaderCreator<T>)creator).createFromParcel(this, loader); } return creator.createFromParcel(this); } 

As you can see, the last call to this method simply calls the right Creator , but inside readParcelableCreator there is a lot of reflection that can be avoided by simply calling it directly.

This utility may be useful:

 import android.os.Parcel; import android.os.Parcelable; public class Parcels { public static void writeBoolean(Parcel dest, Boolean value) { dest.writeByte((byte) (value != null && value ? 1 : 0)); } public static Boolean readBoolean(Parcel in){ return in.readByte() != 0; } public static void writeParcelable(Parcel dest, int flags, Parcelable parcelable) { writeBoolean(dest, parcelable == null); if (parcelable != null) { parcelable.writeToParcel(dest, flags); } } public static <T extends Parcelable> T readParcelable(Parcel in, Parcelable.Creator<T> creator) { boolean isNull = readBoolean(in); return isNull ? null : creator.createFromParcel(in); } } 
+10
Sep 15 '14 at 15:47
source share

Line:

 obj = (A)in.readParcelable(A.class.getClassLoader()); 

should change to:

 obj = (A)in.readParcelable(B.class.getClassLoader()); 

I ran into the same problem and several google searches, many web pages or tutorials suggest that we use A.class.getClassLoader() because we send A, but in fact it is WRONG because you get a null value, we should use B.class.getClassLoader() because codes are INSIDE class B I just did not know why, but it can get the correct object A in this way.

Welcome to comment and confirm!

+2
Feb 07 '14 at 6:01
source share



All Articles