Search code examples
javaandroidparcel

Writing/Reading arrays or Stringarrays in Parcelable


In order to pass an object between 2 activities in my app, i made the class implement Parcable and everything works fine. Now I want to extend this class with an Array of String Arrays (String[][]).

I searched the internet for some time but i couldn't find a way to handle this at writeToParcel(Parcel dest, int flags) and in the Constructor MyClass(Parcel in).

Another option would be to create a class with just 2 Strings stringA and stringB and let that class implement Parcable, too. Then i could use readList() and writeList() to write lists of that Parcables but this doesnt seem to be an ideal solution.

Any suggestions?


Solution

  • The Parcel class has a writeStringArray() method. Couldn't your class iterate over the String[][] and call writeStringArray for each?

    Assuming your class has a member:

    String[][] data;
    

    in writeToParcel()

    parcel.writeInt(data.length);
    for( int i=0; i<data.lengh; i++ ){
        parcel.writeStringArray(data[i]);
    }
    

    in createFromParcel()

    int size = parcel.readInt();
    data = new String[size][];
    for( int i=0; i<size; i++ ){
      data[i] = parcel.readStringArray();
    }