将列表传递给另一个活动

时间:2017-06-10 13:28:26

标签: android android-intent arraylist

我正在尝试将列表传递给下一个活动,但是它给了我一个classcast异常我该如何解决呢?我在模型类中实现了serializable。 有人帮我解决了这个问题。

List<PagesSqliteData>pagesSqliteDataArrayList = new ArrayList<>();
            PagesSqliteData pagesSqlite = new PagesSqliteData();
        pagesSqlite.setToc_name(bookingsSqliteDataArrayList.get(position).getToc_name());
         pagesSqlite.setCompletion(bookingsSqliteDataArrayList.get(position).getCompletion());

        pagesSqlite.setCategory_id(bookingsSqliteDataArrayList.get(position).getCategory_id());

        pagesSqlite.setBooking_id(bookingsSqliteDataArrayList.get(position).getBooking_id());
        pagesSqlite.setTable_of_content_id(bookingsSqliteDataArrayList.get(position).getTable_of_content_id());

        pagesSqliteDataArrayList.add(pagesSqlite);

        Intent i = new Intent(MyBookings.this, Pages.class);
            i.putExtra("LIST",pagesSqliteDataArrayList);
            startActivity(i);
    }

在下一个活动中这样取得:

PagesSqliteData details = (PagesSqliteData)getIntent().getSerializableExtra("LIST");

2 个答案:

答案 0 :(得分:0)

出于一个简单的原因,你得到了ClassCastException。查看代码的这个注释版本:

List<PagesSqliteData>pagesSqliteDataArrayList = new ArrayList<>();//HERE YOU CREATE AN ARRAYLIST!!!
        PagesSqliteData pagesSqlite = new PagesSqliteData();
    pagesSqlite.setToc_name(bookingsSqliteDataArrayList.get(position).getToc_name());
     pagesSqlite.setCompletion(bookingsSqliteDataArrayList.get(position).getCompletion());

    pagesSqlite.setCategory_id(bookingsSqliteDataArrayList.get(position).getCategory_id());

    pagesSqlite.setBooking_id(bookingsSqliteDataArrayList.get(position).getBooking_id());
    pagesSqlite.setTable_of_content_id(bookingsSqliteDataArrayList.get(position).getTable_of_content_id());

    pagesSqliteDataArrayList.add(pagesSqlite);

    Intent i = new Intent(MyBookings.this, Pages.class);
        i.putExtra("LIST",pagesSqliteDataArrayList);
        startActivity(i);

加载时:

PagesSqliteData details = (PagesSqliteData)getIntent().getSerializableExtra("LIST");//HERE IT IS SUDDENLY A SINGLE OBJECT

所以当你保存时,忽略arrayList。传递pagesSqlite。并确保此类是Serializable或Parcelable。或者在加载时,将其加载到ArrayList中。你所做的相当于:

PagesSqliteData data = new ArrayList<PagesSqliteData>();

这是你无法做到的事情。

答案 1 :(得分:0)

如果E类型是Serializable,则可以以相同的方式传递ArrayList。

您可以调用Intent的putExtra(String name,Serializable值)来存储,并使用getSerializableExtra(String name)进行检索。

示例:

ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);
In the other Activity:

ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");

[参考:] [How to pass ArrayList<CustomeObject> from one activity to another? 1