我正在尝试将一组自定义对象传递给一个活动。我已经实现了parcelable:
public class WidgetState {
static class Light implements Parcelable
{
int id;
String text;
int offColor,onColor;
boolean on=false;
boolean isRows;
int size;
public static final Parcelable.Creator<Light> CREATOR = new Parcelable.Creator<Light>() {
public Light createFromParcel(Parcel in) {
return new Light(in);
}
public Light[] newArray(int size) {
return new Light[size];
}
};
@Override
public int describeContents() {
return 0;
}
public Light(Parcel src)
{
id = src.readInt();
text = src.readString();
offColor = src.readInt();
onColor = src.readInt();
on = src.readInt()==1;
isRows = src.readInt()==1;
size = src.readInt();
}
public Light() { }
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(text);
dest.writeInt(offColor);
dest.writeInt(onColor);
dest.writeInt(on?1:0);
dest.writeInt(isRows?1:0);
dest.writeInt(size);
}
}
}
我可以在启动活动中将单个对象放入包中,并通过
检索它bundle.putParcelable(new WidgetState.Light(),"light");
并通过
在结果活动中检索它WidgetState.Light light = (WidgetState.Light)getIntent().getExtras().getParcelable("light")
但是像这样包装和数组
bundle.putParcelableArray(new WidgetState.Light[4],"lights");
我可以在第一个活动
上做到这一点WidgetState.Light[] lights = (WidgetState.Light[])bundle.getParcelableArray("lights");
intent.putExtras(bundle);
startActivityForResult(intent,1);
但是在第二个活动中,当我调用
时,我得到一个RuntimeExceptionWidgetState.Light [] lights = (WidgetState.Light []) state.getParcelableArray("lights");
这是第一个活动中的所有代码
Intent intent = new Intent(MainActivity.this,GuiActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("light", new WidgetState.Light());
bundle.putParcelableArray("lights", new WidgetState.Light[4]);
WidgetState.Light[]lights = (WidgetState.Light[])bundle.getParcelableArray("lights");
intent.putExtras(bundle);
startActivityForResult(intent,1);
第二个
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gui);
Bundle state = (savedInstanceState!=null)?savedInstanceState:getIntent().getExtras();
try {
WidgetState.Light light = (WidgetState.Light) state.getParcelable("light");
// Throws RuntimeException on next line
WidgetState.Light [] lights = (WidgetState.Light []) state.getParcelableArray("lights");
Toast.makeText(this, "Good bundle", Toast.LENGTH_SHORT).show();
}
catch ( RuntimeException e)
{
Toast.makeText(this, "Failed to read bundle", Toast.LENGTH_SHORT).show();
}
}
我错过了什么?