Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 628
Andrew Bennett Avatar asked Dec 20 '12 23:12

Andrew Bennett


2 Answers

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.

like image 54
Maxim Shoustin Avatar answered Oct 01 '22 16:10

Maxim Shoustin


Just cast the serializable you retrieved from the bundle to a List, create a new Stack, and then add all the List items to the stack:

Serializable serializable = savedInstanceState.getSerializable("key");
List<Something> list = (List<Something>) serializable;
Stack<Something> stack = new Stack<Something>();
stack.addAll(list);

Why cast to List and not ArrayList you ask? Because if this is fixed in some Android version, you won't have a ClassCastException again.

like image 36
AlikElzin-kilaka Avatar answered Oct 01 '22 14:10

AlikElzin-kilaka