How to pass object to between Activity objects without using Serializable or Parcelable
Using Parcelable to pass objects between Activity objects is the correct way to do so. However, occasionally developers may encounter the scenario where the object you want to pass has its class defined in another library which you don't have access to the source code. In this case, you cannot implements Serializable or Parcelable interfaces.
In this case, you can create a wrapper class implement the interfaces. But if you don't want to do this, there is another solution as well. You can use JSON to solve this problem. In sender activity, convert the object you want to pass to JSON string. And in receiver activity, convert the JSON string back to the object.
Code in sender activity:
Intent intent = new Intent(this, ReceiverActivity.class);
Bundle bundle = new Bundle();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
String objectToPassStr = gson.toJson(objectToPass); // Convert object to JSON
bundle.putString("param", objectToPassStr);
intent.putExtras(bundle);
this.startActivity(intent);
Code in receiver activity:
Bundle bundle = getIntent().getExtras();
String objectToPassStr = bundle.getString("param");
Gson gson = builder.create();
ObjectToPass objectToPass = gson.fromJson(objectToPassStr, ObjectToPass.class) // Convert
JSON to object
So now you can use objectToPass in the receiver activity. However using Parcelable is still better solution if you can find a way to use it.
Comments
Post a Comment