2

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!

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
LimpSquid
  • 327
  • 6
  • 17
  • 1
    assuming you have complete control over the "fragmentList", yes. – jtahlborn Jul 25 '14 at 19:16
  • A dynamic check whether the object is indeed an ArrayList and whether each element is indeed a Fragment is not very expensive. In case something *does* go wrong, this might give you a better diagnostic. (We all know good old Murphy ;-) – laune Jul 25 '14 at 19:31
  • I do have complete control over the fragmentList indeed. I will try to do a dynamic check if each element is indeed a Fragment. If done, can I just simply suppress the warning? – LimpSquid Jul 25 '14 at 23:01

1 Answers1

1

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!!!

petey
  • 16,914
  • 6
  • 65
  • 97
  • that is exactly what I am doing, did not post it because I thought it wouldn't make sense if you're not seeing my whole code. That's why I put the ArrayList there. I used Serializable for the sake of simplicity. I don't really need to send the data fast, however I will take a look at Parcelable. – LimpSquid Jul 25 '14 at 22:56