开发者

How to put a List in intent

开发者 https://www.devze.com 2023-03-16 19:21 出处:网络
I have开发者_如何学JAVA a List in one of my activities and need to pass it to the next activity.

I have开发者_如何学JAVA 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消