我正在尝试使用intent.puExtra函数将HashMap传递给新活动.单步执行调试器似乎它添加了HashMap没有问题,但是当调用startActivty()时,我得到一个运行时错误,指出Parcel:无法编组值com.appName.Liquor.
Liquor是我创建的一个自定义类,我相信它与HashMap结合使用会导致问题.如果我传递一个字符串而不是我的HashMap,它加载下一个活动没问题.
主要活动
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String cat = ((TextView) view).getText().toString();
Intent i = new Intent(OhioLiquor.this, Category.class);
i.putExtra("com.appName.cat", _liquorBase.GetMap());
startActivity(i);
Run Code Online (Sandbox Code Playgroud)
酒类
public class Liquor
{
public String name;
public int code;
public String category;
private HashMap<String, Bottle> _bottles;
public Liquor()
{
_bottles = new HashMap<String, Bottle>();
}
public void AddBottle(Bottle aBottle)
{
_bottles.put(aBottle.size, aBottle);
}
}
Run Code Online (Sandbox Code Playgroud)
子活动
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
HashMap<Integer, Liquor> map = (HashMap<Integer, Liquor>)getIntent().getSerializableExtra("com.appName.cat"); …Run Code Online (Sandbox Code Playgroud) 我有一个实现了Parcelable的类.我可以执行以下操作来创建类的新实例吗?:
Foo foo = new Foo("a", "b", "c");
Parcel parcel = Parcel.obtain();
foo.writeToParcel(parcel, 0);
Foo foo2 = Foo.CREATOR.createFromParcel(parcel);
Run Code Online (Sandbox Code Playgroud)
我希望foo2成为foo的克隆.
----------------------更新--------------------------- ----
以上不起作用(在新实例中所有Foo成员都为null).我在活动之间传递Foos就好了,所以Parcelable接口实现正常.使用以下工作:
Foo foo1 = new Foo("a", "b", "c");
Parcel p1 = Parcel.obtain();
Parcel p2 = Parcel.obtain();
byte[] bytes = null;
p1.writeValue(foo1);
bytes = p1.marshall();
p2.unmarshall(bytes, 0, bytes.length);
p2.setDataPosition(0);
Foo foo2 = (Foo)p2.readValue(Foo.class.getClassLoader());
p1.recycle();
p2.recycle();
// foo2 is the same as foo1.
Run Code Online (Sandbox Code Playgroud)
从以下q中找到了这个:如何在Android中使用Parcel?
这工作正常,我可以使用它,但它是额外的代码,不确定是否有更短的方法来做到这一点(除了正确实现一个复制构造函数...).
谢谢
我有一个具有嵌套性质的Bundle,我想保留,我怎样才能最容易地保留整个Bundle?SharedPreferences缺乏捆绑功能.