Android Packageable: How to read/write string array lists and integer arrays
I’m having trouble trying to write a list of string arrays and integer arrays to a package.
Here is my class field
String uniqueDate;
ArrayList <String> set1Numbers;
ArrayList <String> set2Numbers;
ArrayList <String> UIDs;
int[] selectedStatus;
This part is writing 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);
}
Read it in this part. I think that’s the problem
PNItems(Parcel in)
{
this.uniqueDate = in.readString();
in.readStringList(set1Numbers);
in.readStringList(set2Numbers);
in.readStringList(UIDs);
in.readIntArray(selectedStatus);
}
Can anyone tell me how to do it, I couldn’t find a tutorial online that solved my problem.
Solution
If you look at <a href=”http://developer.android.com/reference/android/os/Parcel.html#readStringList(java.util.List<java.lang.String>)” rel=”noreferrer noopener nofollow”> the documentation For Parcel, readStringList() displays
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<> you pass in is non-empty (because it will populate it). Since this is your constructor, I want your arguments to be empty, that’s why you crashed. You should use Parcel instead #createStringArrayList()
returns 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();