Unchecked cast: 'java.io.Serializable' to 'java.util.ArrayList<android.app.Fragment>'

LimpSquid picture LimpSquid · Jul 25, 2014 · Viewed 7.3k times · Source

I am getting an unchecked cast warning and I am not sure if it is safe to suppress it.

I am putting an ArrayList<Fragment> inside a Bundle. This Bundle is then put in my Intent as following:

Intent mIntent = new Intent(getBaseContext(),MySecondActivity.class);
Bundle myBundle = new Bundle();
myBundle.putSerializable("fragmentList",ArrayList<Fragment>);
mIntent.putExtras(myBundle);
startActivity(mIntent);

Then on my new activity (MySecondActivity) I am retrieving this data with the following code:

(ArrayList<Fragment>) getIntent().getSerializableExtra("fragmentList")

My compiler gives me the following warning:

" Unchecked cast: 'java.io.Serializable' to 'java.util.ArrayList' "

Everything is working fine though, am I right to say I can safely suppress it?

Thank you!

Answer

petey picture petey · Jul 25, 2014

Fragments are not Serializable, same for ArrayLists of Fragments. So, putSerializable in this will not work, ever. even if they were serializable you would still need to use the method correctly. something like:

ArrayList<Fragment> fragmentArrayList = new ArrayList<Fragment>();
fragmentList.add(foo);
...
myBundle.putSerializable("fragmentList", fragmentArrayList);  //not ArrayList<Fragment>

Instead try,

  1. have MySecondActivity create these fragments you wanted to pass to it in the onCreate
  2. Place the data classes you want to pass to MySecondActivity in the bundle for that intent, but implement Parcelable instead since it is a quicker/better than Serializable

For step two, here is a tutorial about making your data classes implement Parcelable

HTHs!!!