I don't get why this ClassCastException occurs

Use this method, it work for me.

Parcelable[] ps = getIntent().getParcelableArrayExtra();
Uri[] uri = new Uri[ps.length];
System.arraycopy(ps, 0, uri, 0, ps.length);

Unfortunately there is no way to cast like that for arrays in Java. You will have to iterate your array and cast each object individually.

The reason for this is type Safety, the JVM simply cannot ensure that the contents of your array can be casted to Uri, without having to iterate thru them, which is why you have to iterate them and cast them individually.

Basically because Parcelable could be inherited by other Objects, there is no guarantee that the Array contains only Uri objects. However casting to a supertype would work since then type safety would be ok.


Arrays do have polymorphic behaviour - only generic types don't have.

That is, if Uri implements Parcelable then

you CAN say:

Parcelable[] pa = new Uri[size];
Uri[] ua = (Uri[]) pa;

you CANNOT say:

List<Parcelable> pl = new ArrayList<Uri>();

As you see we can cast pa back to Uri[]. Then what is the problem? This ClassCastException happens when your app is killed and later the saved array is recreated. When it is recreated the runtime does not know what kind of array (Uri[]) it was so it just creates a Parcelable[] and puts elements into it. Hence the ClassCastException when you try to cast it to Uri[].

Note that the exception does not happen (theoretically) when the process is not killed and the originally created array (Uri[]) is reused between state save/restore rounds. Like when you change the orientation.

I just wanted to make clear WHY it happened. If you want a solution @solo provided a decent one.

Cheers