Search code examples
androidserializationbundle

When using an android bundle, why does a serialised stack deserialise as an ArrayList?


Serialisation:

Bundle activityArguments = new Bundle();
Stack<Class<? extends WizardStep>> wizardSteps = new Stack<Class<? extends WizardStep>>();
wizardSteps.push(CreateAlarmStep5View.class);
wizardSteps.push(CreateAlarmStep4View.class);
wizardSteps.push(CreateAlarmStep3View.class);
wizardSteps.push(CreateAlarmStep2View.class);
wizardSteps.push(CreateAlarmStep1View.class);
        
activityArguments.putSerializable("WizardSteps", wizardSteps);

Deserialisation:

Stack<Class<? extends WizardStep>> wizardSteps = 
(Stack<Class<? extends WizardStep>>) getIntent().getExtras().getSerializable("WizardSteps");

Exception:

12-20 23:19:45.698: E/AndroidRuntime(12145): Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Stack


Solution

  • Its known bug. I surprise that it still exists.

    Use generic container like:

    public class SerializableHolder implements Serializable {
    private Serializable content;
    public Serializable get() {
        return content;
    }
    public SerializableHolder(Serializable content) {
        this.content = content;
     }
    }
    

    If you use GSON library, convert your Stack to String and use as single String for Bundle without Serialize. It should work.