Java AndroidRuntime 错误:包裹:无法编组值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3818745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 05:26:51  来源:igfitidea点击:

AndroidRuntime error: Parcel: unable to marshal value

javaandroid

提问by Jared

I am trying to pass a HashMap to a new activity using the intent.puExtra function. Stepping through the debugger it seems that it adds the HashMap no problem, however when startActivty() is called I get a runtime error stating that Parcel: unable to marshal value com.appName.Liquor.

我正在尝试使用 intent.puExtra 函数将 HashMap 传递给新活动。通过调试器,它似乎添加了 HashMap 没有问题,但是当 startActivty() 被调用时,我收到一个运行时错误,指出 Parcel:无法编组值 com.appName.Liquor。

Liquor is a custom class that I created, and I believe it, in combination with a HashMap, is causing the problem. If I pass a string rather than my HashMap it loads the next activity no problem.

Liquor 是我创建的自定义类,我相信它与 HashMap 结合会导致问题。如果我传递一个字符串而不是我的 HashMap,它会加载下一个活动没问题。

Main Activity

主要活动

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

Liquor Class

酒类

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

Sub Activity

子活动

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    HashMap<Integer, Liquor> map = (HashMap<Integer, Liquor>)getIntent().getSerializableExtra("com.appName.cat");

    setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, GetNames(map)));

    ListView lv = getListView();
    lv.setTextFilterEnabled(true);

When the runtime error exists it never makes it into the sub activity class. So I'm pretty sure the problem exists in the adding of the HashMap to the intent, and based off the error I believe my Liquor class is the cause, but I can't figure out why.

当运行时错误存在时,它永远不会进入子活动类。所以我很确定问题存在于将 HashMap 添加到意图中,并且基于错误,我相信我的 Liquor 类是原因,但我不知道为什么。

Your help will be much appreciated. Thanks!

您的帮助将不胜感激。谢谢!

采纳答案by naikus

Your HashMapitself is serializable but is the Bottleclass serializable? If not, it will not serialize and will throw errors at runtime. Make the Bottleclass implement the java.io.Serializableinterface

HashMap本身是可序列化的,但Bottle类是可序列化的吗?如果不是,它不会序列化并在运行时抛出错误。使Bottle类实现java.io.Serializable接口