问题
Can you tell me how to solve this? It throws a bad array length exception and after debugging, I found this method throws the Exception:
--------------------------My Code-----------------------------------
public class SingleModels implements Parcelable{
public String name;
public String[] names ;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeStringArray(names);
}
public static final Parcelable.Creator<SingleModels> CREATOR = new Creator<SingleModels>() {
@Override
public SingleModels[] newArray(int size) {
return new SingleModels[size];
}
@Override
public SingleModels createFromParcel(Parcel source) {
SingleModels models = new SingleModels();
models.name = source.readString();
models.names = source.createStringArray();
source.readStringArray(models.names);
return models;}
};
}
This is my exception, but so long, I can't upload the image, I cut the information by important:
07-07 09:52:59.319: E/AndroidRuntime(4296): FATAL EXCEPTION: main
07-07 09:52:59.319: E/AndroidRuntime(4296): java.lang.RuntimeException: Unable to start activity ComponentInfo{edu.single.parcelable.example/edu.single.parcelable.example.ArrayParcelable_Activity}: java.lang.RuntimeException: bad array lengths
07-07 09:52:59.319: E/AndroidRuntime(4296): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
回答1:
This is the implementation of readStringArray()
:
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 seems as though the length of your models.names
array is the reason it's throwing that error. You need to know the exact size of your array beforehand to create the array so that it doesn't throw the error.
I think createStringArray()
suffices, you don't need to call source.readStringArray(models.names);
so just delete that and it should work.
I think there may be a language barrier here, so i'll mention the exact code you should have:
@Override
public SingleModels createFromParcel(Parcel source) {
SingleModels models = new SingleModels();
models.name = source.readString();
models.names = source.createStringArray();
return models;
}
来源:https://stackoverflow.com/questions/24607543/android-parcelable-readstringarray-bad-array-lengths