Skip to content Skip to sidebar Skip to footer

Passing Parcelable Object Which Has A Member Variable Which Is Not Parcelable(a Class That Belongs To Third Party Library)

I'm trying to send a class's object(let's say Class X's object) as part of class that implements Parcelable. The problem that I am facing here is, Class X is a part of some library

Solution 1:

If you cannot implement Parcelable or Serializable, there is only one option left: passing the object through global state.

Using static fields

Add a static field of the type RandomClass to DummyParcelableObject, e.g. randomClassStatic. Set it just before starting the service:

// Start the service.
DummyParcelableObject mObj = new DummyParcelableObject(new RandomClass(2019));
Intent serviceIntent = new Intent(MainActivity.this, SampleService.class);
serviceIntent.putExtra("myObj", mObj);
DummyParcelableObject.randomClassStatic = mObj.getRandomClass();
startService(serviceIntent);

Then retrieve it right after the service started in onStartCommand():

DummyParcelableObject obj = intent.getParcelableExtra("mObj");
obj.setRandomClass(DummyParcelableObject.randomClassStatic);
DummyParcelableObject.randomClassStatic = null;

You would need to define getRandomClass() and setRandomClass() accordingly for getting / setting mRandomClass.

Note that this is not the safest thing to do in regard of concurrency, objects' life cycles, etc…

Using the Application class

This can only be used if you have access to an Activity or Service on both ends.

Subclass Application and add a field of type RandomClass to it. It will serves as relay. Define public methods for getting / setting this field (e.g. getRandomClass() and setRandomClass()). Do not forget to reference your subclassed Application in the manifest as described here. Before starting the service:

// Start the service.
DummyParcelableObject mObj = new DummyParcelableObject(new RandomClass(2019));
Intent serviceIntent = new Intent(MainActivity.this, SampleService.class);
serviceIntent.putExtra("myObj", mObj);
((MyApplication) getApplication()).setRandomClass(mObj.getRandomClass());
startService(serviceIntent);

Then for retrieving the object once the service started, still in onStartCommand():

DummyParcelableObject obj = intent.getParcelableExtra("mObj");
obj.setRandomClass(((MyApplication) getApplication()).getRandomClass());
DummyParcelableObject.randomClassStatic = null;

This has the benefit of not using a static field, but can still be a source of bugs if handled poorly (thread safety, no checks on nullity, …).


Post a Comment for "Passing Parcelable Object Which Has A Member Variable Which Is Not Parcelable(a Class That Belongs To Third Party Library)"