user790431
user790431

Reputation:

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?

Upvotes: 9

Views: 25075

Answers (5)

deathangel908
deathangel908

Reputation: 9699

Everyone says that you can use Serializable, but none mentioned that you can just cast the value to Serializable instead of list.

intent.putExtra("selectedData", (Serializable) selectedData);

Core's lists implementations already implement Serializable, so you're not bound to a specific implementation of list, but remember that you still can catch ClassCastException.

Upvotes: 0

Ronny K
Ronny K

Reputation: 3731

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.

Upvotes: 1

hsson
hsson

Reputation: 615

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);

Upvotes: 14

Octavian Helm
Octavian Helm

Reputation: 39604

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.

Upvotes: 11

Nissan911
Nissan911

Reputation: 293

i think ur item should be parcelable. and you should use arraylist instead of list. then use intent.putParcelableArrayListExtra

Upvotes: 4

Related Questions