Android Parcelable: how to read / write string arrays and integer arrays

I am having trouble trying to write lists of String arrays and integer arrays to send.

these are the fields of my class

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

      

This part writes data to the 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. 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 this, I couldn't find a tutorial on the internet with my problem. Thanks for reading

+3


source to share


1 answer


If you look at the documentation for Parcel readStringList () shows:

Reading into data List List String objects that were written with writeStringList (List) in the current dataPosition () object.

Returns A newly created ArrayList containing strings with the same data as previously written.

This requires the List <> you passed in to be non-null (as it will fill it). Since this is your constructor, I would expect your parameters to be zero, which is why you crash. Instead, you should use Parcel#createStringArrayList()

to return a new list:



Read and return a new ArrayList containing String objects from the posting that was written with writeStringList (List) in the current dataPosition (). Returns null if the previously written list object was null.

Returns A newly created ArrayList containing strings with the same data as previously written.

For example:

set1Numbers = in.createStringArrayList();

      

+6


source







All Articles