Using Parcelable on a Library Class

1.2k views Asked by At

I want to send an object between Activities. Reading up on this i have come to conclusion that using Parcelable is the best way to go as it has the least performance impacts. The reason i want to do this is because i need to download data from the network to create an Object, so i don't want to keep downloading the data.

However, in order to use a Parcel the class needs to implement Parcelable. As i am trying to send an Object defined in a Library i cannot edit the class to include this.

What would be the best way to solve my predicament?

I have tried extending the library class and implementing Parcelable but failed with a ClassCastException. I have also seen mentioned that i should make a Parcelable class that wraps around my library class and send it that way?

Thanks!

2

There are 2 answers

0
serv-inc On

How about using the parceler library? You can tell your Application to parcel library classes:

@ParcelClass(LibraryParcel.class)
public class AndroidApplication extends Application{
    //...
}

If that works, you could use the following code to wrap/unwrap:

Parcelable wrapped = Parcels.wrap(new Example("Andy", 42));
Example example = Parcels.unwrap(wrapped);
example.getName(); // Andy
example.getAge(); // 42
0
Viacheslav Okolitiy On

Did you try to use Bundle ?

For example if you have parcelable class User

Bundle bundle = new Bundle();
List<User> users = new ArrayList<User>();
String userName = user.setUserName("some name");
boolean isOnline = user.setOnline(true);
users.add(user);
bundle.putParcelableArrayList("USER", users);

And you may retrieve this as:

public ArrayList<User> getParcelableArrayList(Bundle bundle){
   List<User> userList = new ArrayList<User>();
   userList = bundle.getParcelableArrayList("USER");
}