Malvinka
Malvinka

Reputation: 1379

putExtras(child class) - receiving base class

I've got class Playlist extends ArrayList I use in

Playlist playlist = new Playlist(); 
intent.putExtra("playlist", playlist); 

and then I try to get it back:

if (getIntent().hasExtra("playlist")) {
    playlist = (Playlist)(getIntent().getExtras().getStringArrayList("playlist"));
}

but I receive an error: Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to pl.mal.player.Playlist. I know that to problem is I would like to cast base class to child class. But I do not know how to avoid it in this example. Can someone help me?

Upvotes: 0

Views: 36

Answers (2)

danny117
danny117

Reputation: 5651

Your playlist class will have to implement parcelable to pass it in an extra.

http://developer.android.com/reference/android/os/Parcelable.html

How can I make my custom objects Parcelable?

Upvotes: 0

zapl
zapl

Reputation: 63955

The getStringArrayList can't return you a Playlist Object. You will have to do something like

List<String> list = getIntent().getExtras().getStringArrayList("playlist");
Playlist playlist = new Playlist();
playlist.addAll(list);

You can only cast an object to super classes & interfaces implemented by the concrete runtime type. That's ArrayList in this case. If you wanted to change that you'd have to modify the getStringArrayList method because something in there says explicitly new ArrayList

Upvotes: 1

Related Questions