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!

3
  • 1
    assuming you have complete control over the "fragmentList", yes. Commented Jul 25, 2014 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 ;-) Commented Jul 25, 2014 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? Commented Jul 25, 2014 at 23:01

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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 <Fragment> 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.