Android Deserialize Object?

Android Deserialize Object?

how to deserialize this type:

public Intent putExtra(String name, Serializable value)

example:

 intent.putExtra("activityToPass", GoToThisActivity.class);
 ???
 getIntent().getExtras.getSerializable("activityToPass");

how to do this please;

please help!!

1 Answer

If you want to pass a custom object from one activity to the other, first you must have your custom object's class to implement java.io.Serializable:

public class SomeObject implements Serializable {
    private String name;
    public SomeObject (final String name) {
        this.name = name;
    }
    [...]
}

final SomeObject myExtra = new SomeObject("any name");

Then you can add this myExtra to the intent with which you call your new Activity:

final Intent intent = new Intent(this, GoToThisActivity.class);
intent.putExtra("serializedExtra", myExtra);
startActivity(intent);

Inside your GoToThisActivity class' onCreate method you can extract this extra as:

final Intent intent = getIntent();
if (intent.hasExtra("serializedExtra"))
    final SomeObject myExtra= (SomeObject)intent.
        getSerializableExtra("serializedExtra");
    [...]
}

And now you have your custom object in your new activity.

Update 1: Passing a class to an other activity with Intent
If you want to pass a Class instance to an intent:

intent.putExtra("classExtra", GoToThisActivity.class);

and to deserialize it in the other activity:

if (intent.hasExtra("classExtra"))
{
    final Class<?> classExtra= (Class<?>)intent.
        getSerializableExtra("classExtra");
    [...]
}

Update 2:
When deserializing an array of custom objects, you have to make sure, that the elements in that array implement the Serializable interface.

To stay at your sample:

public class ButtonPick implements Serializable
{
    public static final ButtonPick EDIT = new ButtonPick();
    public static final ButtonPick DELETE = new ButtonPick();
}

You put the extra in the Intent:

intent.putExtra("buttonPicks", new ButtonPick[]
    {ButtonPick.DELETE,ButtonPick.EDIT});

And inside the other activity deserialize it:

if (intent.hasExtra("buttonPicks"))
{
    final Object[] buttonPicks= (Object[])intent.
        getSerializableExtra("buttonPicks");
        [...]
}

You MUST cast the array as Object[] regardless to the original being ButtonPicks[].
The elements inside the array have their proper type, so inside are the

{ ButtonPicks.EDIT, ButtonPicks.DELETE }

members.
You need to cast them individually.

7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.