0

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?

Malvinka
  • 1,185
  • 1
  • 15
  • 36

2 Answers2

1

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

zapl
  • 63,179
  • 10
  • 123
  • 154
  • During this time I found similar solution - overriding a constructor so it can get an arraylist. Thanks a lot! – Malvinka Oct 28 '14 at 21:01
0

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?

Community
  • 1
  • 1
danny117
  • 5,581
  • 1
  • 26
  • 35
  • That might not work for classes that inherit from `ArrayList` - https://code.google.com/p/android/issues/detail?id=3847 – zapl Oct 28 '14 at 21:26