Android Parcelable readStringArray糟糕的数组长度

时间:2014-07-07 09:42:50

标签: android arrays parcelable

你能告诉我怎么解决这个问题吗?它抛出一个错误的数组长度异常,在调试之后,我发现这个方法抛出异常:

--------------------------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;}
    };
}

这是我的例外,但是这么久,我无法上传图片,我重要的是剪切了信息:

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 个答案:

答案 0 :(得分:2)

这是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");
    }
}

因此,似乎models.names数组的长度是它抛出该错误的原因。您需要事先知道数组的确切大小才能创建数组,这样就不会抛出错误。

我认为createStringArray()已足够,您无需致电source.readStringArray(models.names);,因此只需删除它即可。


我认为这里可能存在语言障碍,所以我会提到你应该拥有的确切代码:

@Override
    public SingleModels createFromParcel(Parcel source) {
        SingleModels models = new SingleModels();
        models.name = source.readString();
        models.names = source.createStringArray();
        return models;
}