0x52616A657368
0x52616A657368

Reputation: 378

Passing custom class objects using parcelable

How can i access custom class object in a class implementing parcelable

I have a parcelable class as folows

class A implements Parcelable{
      private CustomClass B;
}

Is it possible to use that custom class as a normal variable during writeToParcel() and readParcel(Parcel in)

PS: I can't implement parcelable on class B as it is in Non-Android module

Upvotes: 1

Views: 3230

Answers (2)

Ben P.
Ben P.

Reputation: 54274

In your comment you say that CustomClass is made of 4 integer variables. You could therefore do something like this:

class A implements Parcelable {

    private CustomClass B;

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(B.getFirst());
        dest.writeInt(B.getSecond());
        dest.writeInt(B.getThird());
        dest.writeInt(B.getFourth());
    }

    private A(Parcel in) {
        B = new CustomClass();
        B.setFirst(dest.readInt());
        B.setSecond(dest.readInt());
        B.setThird(dest.readInt());
        B.setFourth(dest.readInt());
    }
}

Upvotes: 2

Rajan Kali
Rajan Kali

Reputation: 12953

First you need to make your CustomClass parcelable as in

class CustomClass implements Parcelable{
   // write logic to write and read from parcel
}

Then, in your class A

class A implements Parcelable{
      private CustomClass B;

       @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeParcelable(B, flags); // saving object 
    }

    private A(Parcel in) {
        this.B= in.readParcelable(CustomClass.class.getClassLoader()); //retrieving from parcel
    }
}

EDIT

If you can't make CustomClass as Parcelable, convert class as Json String using google gson and write it to Parcel and while reading, read String and convert back to object

class A implements Parcelable{
      private CustomClass B;

       @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(new Gson().toJson(B), flags); // saving object 
    }

    private A(Parcel in) {
        this.B= new Gson().fromJson(in.readString(),CustomClass.class); //retrieving string and convert it to object and assign
    }
}

Upvotes: 7

Related Questions