Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

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.

like image 470
user3364963 Avatar asked Jan 10 '23 23:01

user3364963


1 Answers

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

Read into the given List items String objects that were written with writeStringList(List) at the current dataPosition().

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

It requires that the List<> that you pass in is non-null (as it will populate it). Since this is your constructor, I would expect that your parameters are null, and that is why you crash. You should instead use Parcel#createStringArrayList() to return a new List:

Read and return a new ArrayList containing String objects from the parcel that was written with writeStringList(List) at 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 those that were previously written.

For example:

set1Numbers = in.createStringArrayList();
like image 153
Kevin Coppock Avatar answered Jan 21 '23 04:01

Kevin Coppock