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
.
Use createStringArray()
instead of readStringArray(String[])
. It will return the array you need.
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.
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With