如何将List放入intent中

问题描述 投票:7回答:5

我的一个活动中有一个List,需要将其传递给下一个活动。

private List<Item> selectedData;  

我尝试通过以下方式实现此目的:

intent.putExtra("selectedData", selectedData);  

但它没有用。可以做些什么?

android
5个回答
10
投票

您必须首先将List实例化为具体类型。 List本身就是一个界面。

如果您在对象中使用implement the Parcelable interface,则可以使用putParcelableArrayListExtra()方法将其添加到Intent中。


12
投票

就像在评论中提到的howettl一样,如果你使列表中的对象可以序列化,那么它变得非常容易。然后你可以将它放在一个Bundle中,然后你可以把它放在意图中。这是一个例子:

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

4
投票

我认为你的项目应该是可以分配的。你应该使用arraylist而不是list。然后使用intent.putParcelableArrayListExtra


1
投票

这对我有用。

//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() + "");
        }

我希望它对你也有用。


0
投票

每个人都说你可以使用Serializable,但没有人提到你可以将值转换为Serializable而不是list。

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

Core的列表实现已经实现了Serializable,因此您没有绑定到list的特定实现,但请记住,您仍然可以捕获ClassCastException。

© www.soinside.com 2019 - 2024. All rights reserved.