lolix
lolix

Reputation: 1527

Trying to send List object to another activity

I am trying to send a List<Question> to other activity but I am receiving the error "java.util.ArrayList cannot be cast to android.os.Parcelable".

FirstActivity

    List<Question> list;
    list = response.body().items;
    Intent myIntent = new Intent(SearchActivity.this, RestaurantActivity.class);
    myIntent.putExtra("restaurants", (Parcelable) list); 
    SearchActivity.this.startActivity(myIntent);

SecondActivity

    Intent intent = getIntent();
    List<Question> restaurants = intent.getExtras().getParcelable("restaurants");
    textView = (TextView)findViewById(R.id.textView);
    textView.setText(restaurants.get(0).title);

What is the problem?

Upvotes: 1

Views: 375

Answers (1)

clownba0t
clownba0t

Reputation: 1133

The reason it doesn't work is that ArrayList itself does not implement the Parcelable interface. However, some Android classes like Intent and Bundle have been set up to handle ArrayLists provided that the instances they contain are of a class which does implement Parcelable.

So, instead of putExtra, try using the putParcelableArrayListExtra method instead.

You'll need to use get getParcelableArrayListExtra on the other side.

Be aware that this only works with ArrayLists, and the Question class will need to implement Parcelable.

Upvotes: 2

Related Questions