These are my model classes:
public class Animal implements Parcelable{
//parcelable implementation
}
public class Cat extends Animal {
}
public class Dog extends Animal {
}
I want to pass an Array
of Animal from an Activity
to another using Intent.putExtra(String name, Parcelable [] value)
.
So I do this:
List<Animal> animals = new Array[3];
animals[0] = new Dog();
animals[1] = new Cat();
animals[2] = new Dog();
Intent.putExtra("myAnimals", animals ).
When I try to retrieve the array from the other Activity
with:
Parcelable[] p = (Parcelable[])data.getParcelableArrayExtra("myAnimals");
I DON'T get an array like this:
[0]Dog
[1]Cat
[2]Dog
I get an array like this:
[0]Animal
[1]Animal
[2]Animal
I don't understand If my logic is incorrect or when you pass an Array
like mine to an Intent
it is turned into an array of SuperClass
objects.
Thank you.
Try to create a CREATOR
field in every of your subclass, e.g.
public static final Parcelable.Creator<Cat> CREATOR
= new Parcelable.Creator<Cat>() {
public Cat createFromParcel(Parcel in) {
return new Cat(in);
}
public Cat[] newArray(int size) {
return new Cat[size];
}
};
Probably you only have this field in your base class Animal
, so when Android tries to recreate the objects from Parcelable
it can only call the CREATOR
of Animal
, so all your objects are Animals
.