【发布时间】:2015-04-27 21:50:51
【问题描述】:
我试图将一个对象传递给一个意图,我在这里阅读了一篇不同的帖子来使用 Gson。现在它没有显示任何错误并且可以运行。但是当我点击一个按钮时,它只会冻结我的手机。没有抛出异常。
OnCreate {
...
listViewObjects.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Person item = (Person)parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), item.name + " selected\n" + item.status, Toast.LENGTH_SHORT).show();
Gson gson = new Gson();
String json = gson.toJson(item);
PersonDescriptionPage.putExtra("person", json);
startActivity(PersonDescriptionPage);
}
});
}
我最初把它作为一个匿名 Gson 对象的一行
PersonDescriptionPage.putExtra("person", new Gson().toJson(item));
如果我调试它,它会冻结在这一行。所以我然后将它拆分为您在上面的第一个代码块中看到的实例化对象,它冻结在gson.toJson(item)
作为参考,我尝试序列化为 Json 的类是:
public class Person{
String name;
boolean ownIt;
Drawable image;
String status;
int backgroundColor;
public Person(){}
public Person(String n, Drawable d, String s, int b)
{
this.name= n;
this.ownIt = false;
this.image = d;
this.status = s;
this.backgroundColor = b;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.name.toString();
}
}
【问题讨论】:
-
你的 json 对象有多大?
-
不是很大,每个都是list.add(new Person("Fred", getResources().getDrawable(R.drawable.fred207),"sick", Color.rgb(89,168,65) ))) ;
-
PersonDescriptionPage 到底是什么?
-
这是一个 android 活动,包含两个 textView,一个 ImageView 和一个 Switch,但代码永远不会到达它。
-
刚刚修复了它,就我而言,问题是因为我有一个
Context对象。将其标记为transient解决了这个问题。您可能应该将image标记为@Android777 建议的瞬态