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 and I can not edit it to implement Parcelable or serializable.
I've checked that Class X
does not implement Parcelable or serializable and we can not change as well.
Can you guys please help me here?
MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Start the service.
DummyParcelableObject mObj = new DummyParcelableObject(new RandomClass(2019));
Intent serviceIntent = new Intent(MainActivity.this, SampleService.class);
serviceIntent.putExtra("myObj", mObj);
startService(serviceIntent);
}
}
Dummy Parcelable class:
class DummyParcelableObject implements Parcelable {
RandomClass mRandomClass;
public DummyParcelableObject(RandomClass obj) {
mRandomClass = obj;
}
protected DummyParcelableObject(Parcel in) {
mRandomClass = (RandomClass) in.readValue(RandomClass.class.getClassLoader());
}
public static final Creator<DummyParcelableObject> CREATOR = new Creator<DummyParcelableObject>() {
@Override
public DummyParcelableObject createFromParcel(Parcel in) {
return new DummyParcelableObject(in);
}
@Override
public DummyParcelableObject[] newArray(int size) {
return new DummyParcelableObject[size];
}
};
public int getRandomVar() {
int n = 0;
if (mRandomClass != null)
{
System.out.println("Anil: DummyParcelableObject: if (mRandomClass != null) is true.\n");
n = mRandomClass.getNumb();
}
else
{
System.out.println("Anil: DummyParcelableObject: if (mRandomClass != null) is false.\n");
}
return n;
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(mRandomClass);
}
}
Class X that is part of another library:
class RandomClass{
public static int cnt = 0;
private int nRandomNumber = 0;
public RandomClass(int n)
{
nRandomNumber = n;
}
public int getNumb()
{
return nRandomNumber;
}
}
Service that we need to send the data to:
public class SampleService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startid) {
DummyParcelableObject obj = intent.getParcelableExtra("mObj");
if (obj == null) {
System.out.println("\nAnil: ParcelableExtra is null");
}
else {
System.out.println("\nAnil: ParcelableExtra is not null");
System.out.println("\nAnil: obj.getRandomVar() = " + obj.getRandomVar());
}
return START_STICKY;
}
}