【发布时间】:2013-12-01 13:27:25
【问题描述】:
我正在尝试我的第一次 Parcelable 转移,但它并不顺利。这是我的 Parcelable 类:
public class Element implements Parcelable, Serializable {
private static final long serialVersionUID = 1L;
String name;
String id;
byte[] password;
public static final Parcelable.Creator<Element> CREATOR = new Parcelable.Creator<Element>() {
public Element createFromParcel(Parcel source) {
return new Element(source);
}
public Element[] newArray(int size) {
return new Element[size];
}
};
private Element(Parcel in){
name = in.readString();
id = in.readString();
password = new byte[in.readInt()];
in.readByteArray(password);
}
public Element(String name,String id,byte[] password){
this.name=name;
this.id=id;
this.password=password;
}
@Override
public String toString() {
return name;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(id);
dest.writeInt(password.length);
dest.writeByteArray(password);
}
}
如您所见,它是一个简单的 Parcelable,包含 2 个字符串字段和 1 个字节数组。
现在我通过我的主要活动将它发送到第二个活动:
//Inside the main activity
Intent i = new Intent(MainActivity.this, DisplayActivity.class);
i.putExtra("element", (Parcelable)adapter.getItem(pos));
startActivity(i);
然后,我在第二个活动中收到 Parcelable:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.display);
Element e = getIntent().getExtras().getParcelable("element");
//this line makes my app crash. No idea why.
【问题讨论】:
-
你能发布异常吗?
-
不知道怎么弄。我正在使用 AIDE IDE,而 Logcat 什么也没显示...
-
没有理由实现
Serializable和Parcelable。您应该实施其中一个。这可能与您的问题有关,也可能无关。 -
另外,如果您的应用程序崩溃,则 logcat 中肯定存在异常和堆栈跟踪。如果您没有看到它,您可能正在过滤 logcat 并错过了它。确保在调试时没有过滤 logcat。你会错过各种重要/相关的东西。
-
另外,在调用
putExtra()时不要将Element转换为Parcelable。
标签: android android-intent parcelable