Search code examples
androidparcel

How do I know how big to make my array for Parcel.readStringArray()?


I'm getting a null pointer exception when I do this:

    private String[] foo;

    private void readFromParcel(Parcel in) {
        in.readStringArray(foo);
    }

It seems I need to allocate the array first. But how do I know how big to make it? Do I have to write the size first and then read the size first? And isn't the point of having a writeStringArray() method to handle this for me?

From the Android Documentation:

There are a variety of methods for reading and writing raw arrays of primitive objects, which generally result in writing a 4-byte length followed by the primitive data items.

So, if I write the count myself, it's getting written twice. There must be some way of doing this where I am not responsible for managing this.


Solution

  • I know this is not a direct answer, but you can use lists (ArrayList<String>) instead with writeList() and createStringArrayList().

    Or you could use Parcle#createStringArray() to get the array.