我经常使用 Parcelable 和 Bundle 没有问题,但这次我需要在我的 parcelable 对象中包含其他 Parcelable 对象的数组,但不幸的是出了点问题,我得到了 NullPointerException,所以我肯定在 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");