Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the parameter for Parcel.readStringArray()?

I am trying to save the state in my Fragment through the use of Parcelable.

This lead to the following code when I wish to get back the a String array that I saved in the Parcelable:

public MyObject createFromParcel(Parcel in) {
            titles=in.readStringArray(???);
}

Now readStringArray needs a parameter, a String[]... But why? It could just give the Strings that I stored in it. I don't know a priori how many there were, so this sucks. :(

The documentation says the following:

That is, nothing.

EDIT: If anyone has the same problem: I ended up using writeBundle()/readBundle() and putting my String[] into the Bundle.

like image 371
Maarten Avatar asked Dec 27 '12 13:12

Maarten


3 Answers

Use createStringArray() instead of readStringArray(String[]). It will return the array you need.

like image 66
hunyadym Avatar answered Nov 01 '22 08:11

hunyadym


Here is an implementation of this method from Android 4.1.2:

public final void readStringArray(String[] val) {
    int N = readInt();
    if (N == val.length) {
        for (int i=0; i<N; i++) {
            val[i] = readString();
        }
    } else {
        throw new RuntimeException("bad array lengths");
    }
}

So it writes values to given array. And returns nothing.

like image 10
Mikita Belahlazau Avatar answered Nov 01 '22 07:11

Mikita Belahlazau


I think it might be useful to view these two methods, readStringArray(String[] val) and createStringArray() side by side:

Let's look at readStringArray(String[] val) method first. It requires a String[] as a parameter and might result in a NullPointerException if you pass a non-initialised array object (null). Also, you'll have to know exactly the length of the array (N), otherwise you'll get the RuntimeException thrown from the method:

public final void readStringArray(String[] val) {
    int N = readInt();
    if (N == val.length) {
        for (int i=0; i<N; i++) {
            val[i] = readString();
        }
    } else {
        throw new RuntimeException("bad array lengths");
    }
}

Oh the other hand, with createStringArray() you don't need to form and provide a String[] as a parameter, it will be formed for you by the method with the correct length too, so you don't have to worry about either NullPointerException or RuntimeException:

public final String[] createStringArray() {
    int N = readInt();
    if (N >= 0) {
        String[] val = new String[N];
        for (int i=0; i<N; i++) {
            val[i] = readString();
        }
        return val;
    } else {
        return null;
    }
}

All in all, as a result of this basic analysis we can jump to conclusions and say that the second method is better and safer..

like image 3
Sergei Emelianov Avatar answered Nov 01 '22 09:11

Sergei Emelianov