当我尝试在Intent中将Parcelable作为Bundle传递时,Parcelable对象数组会导致NullPointerException

时间:2013-11-04 01:48:16

标签: android parcelable

我经常使用Parcelable和Bundle没有问题,但是这次我需要在我的parcelable对象中包含一个其他Parcelable对象的数组,但不幸的是出了问题而且我得到了一个N​​ullPointerException,所以当然我犯了一些错误Parcelable配置,但我还不明白如何解决它。

这是我的尝试

    public class CarConfig implements Serializable, Parcelable {

    Car cars[];
    int speed;

    public CarConfig(Car[] cars, int speed) {
        super();
        this.cars = cars;
        this.speed = speed;
    }

    public CarConfig() {

    }


    public static Parcelable.Creator<CarConfig> getCreator() {
        return CREATOR;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel arg0, int arg1) {
        arg0.writeParcelableArray(cars, 0);
        arg0.writeInt(speed);
    }

    public static final Parcelable.Creator<CarConfig> CREATOR = new Parcelable.Creator<CarConfig>() {
        public CarConfig createFromParcel(Parcel in) {
            return new CarConfig(in);
        }

        public CarConfig[] newArray(int size) {
            return new CarConfig[size];
        }
    };

    private CarConfig(Parcel in) {
        Parcelable[] p = in.readParcelableArray(Car.class.getClassLoader());
        cars = new Car[p.length];
        for (int i = 0; i < p.length; i++) {
            cars[i] = (Car) p[i];
        }
        speed = in.readInt();

    }

}

这里是错误日志

java.lang.ClassCastException: android.os.Bundle cannot be cast to com.myapp.uk.CarConfig 
at com.myapp.uk.MainActivity.onCreate(MainActivity.java:98)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)

当我尝试使用

获取目标活动中的对象时,崩溃就会发生
Bundle bundle = getIntent().getExtras();
cg = bundle.getParcelable("DataKey");

0 个答案:

没有答案