简体   繁体   English

Android Parcelable:如何读/写字符串数组列表和整数数组

[英]Android Parcelable: How to read / write string array lists and integer arrays

I am having problems trying to write String array lists and integer arrays to parcel. 我在尝试将字符串数组列表和整数数组写入parcel时遇到问题。

this is my class fields 这是我的班级领域

String uniqueDate;
ArrayList <String> set1Numbers;
ArrayList <String> set2Numbers;
ArrayList <String> UIDs;
int[] selectedStatus;

This part writes the data to parcel 此部分将数据写入parcel

public void writeToParcel(Parcel dest, int flags) 
    {
        dest.writeString(uniqueDate);
        dest.writeStringList(set1Numbers);
        dest.writeStringList(set2Numbers);
        dest.writeStringList(UIDs);
        dest.writeIntArray(selectedStatus);
    }

This part reads it. 这部分读了它。 I think the problem is here 我认为问题出在这里

PNItems(Parcel in)
    {
        this.uniqueDate = in.readString();
        in.readStringList(set1Numbers);
        in.readStringList(set2Numbers);
        in.readStringList(UIDs);
        in.readIntArray(selectedStatus);
    }

Can someone please tell me how to do it, I could not find a tutorial on the internet with my problem. 有人可以告诉我该怎么做,我找不到我的问题在互联网上的教程。 Thank you for reading 谢谢你的阅读

If you look at the documentation for Parcel, readStringList() shows: 如果查看Parcel 的文档 ,readStringList()显示:

Read into the given List items String objects that were written with writeStringList(List) at the current dataPosition(). 读入给定的List items在当前dataPosition()中使用writeStringList(List)编写的String对象。

Returns A newly created ArrayList containing strings with the same data as those that were previously written. 返回一个新创建的ArrayList,其中包含与先前写入的数据相同的数据字符串。

It requires that the List<> that you pass in is non-null (as it will populate it). 它要求您传入的List <>非null(因为它将填充它)。 Since this is your constructor, I would expect that your parameters are null, and that is why you crash. 由于这是你的构造函数,我希望你的参数为null,这就是你崩溃的原因。 You should instead use Parcel#createStringArrayList() to return a new List: 您应该使用Parcel#createStringArrayList()来返回一个新的List:

Read and return a new ArrayList containing String objects from the parcel that was written with writeStringList(List) at the current dataPosition(). 从当前dataPosition()使用writeStringList(List)编写的parcel中读取并返回一个包含String对象的新ArrayList。 Returns null if the previously written list object was null. 如果先前写入的列表对象为null,则返回null。

Returns A newly created ArrayList containing strings with the same data as those that were previously written. 返回一个新创建的ArrayList,其中包含与先前写入的数据相同的数据字符串。

For example: 例如:

set1Numbers = in.createStringArrayList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM