How to put a List in intent
I have a List in one of my activities and need to pass it to the next activity.
private List<Item> selectedData;
I tried putting this in intent by :
intent.putExtra("selectedData", selectedData);
But it is not working. What can be done?
Like howettl mentioned in a comment, if you make the object you are keeping in your list serializeable then it become very easy. Then you can put it in a Bundle which you can then put in the intent. Here is an example:
class ExampleClass implements Serializable {
public String toString() {
return "I am a class";
}
}
... */ Where you wanna create the activity /*
ExampleClass e = new ExampleClass();
ArrayList<ExampleClass> l = new ArrayList<>();
l.add(e);
Intent i = new Intent();
Bundle b = new Bundle();
b.putSerializeable(l);
i.putExtra("LIST", b);
startActivity(i);
You have to instantiate the List
to a concrete type first. List
itself is an interface.
If you implement the Parcelable
interface in your object then you can use the putParcelableArrayListExtra()
method to add it to the Intent
.
i think ur item should be parcelable. and you should use arraylist instead of list. then use intent.putParcelableArrayListExtra
This is what worked for me.
//first create the list to put objects
private ArrayList<ItemCreate> itemsList = new ArrayList<>();
//on the sender activity
//add items to list where necessary also make sure the Class model ItemCreate implements Serializable
itemsList.add(theInstanceOfItemCreates);
Intent goToActivity = new Intent(MainActivity.this, SecondActivity.class);
goToActivity.putExtra("ITEMS", itemsList);
startActivity(goToActivity);
//then on second activity
Intent i = getIntent();
receivedItemsList = (ArrayList<ItemCreate>) i.getSerializableExtra("ITEMS");
Log.d("Print Items Count", receivedItemsList.size()+"");
for (Received item:
receivedItemList) {
Log.d("Print Item name: ", item.getName() + "");
}
I hope it works for you too.