gpt4 book ai didi

android - Parcelable 传输失败

转载 作者:行者123 更新时间:2023-11-29 14:15:11 25 4
gpt4 key购买 nike

我正在尝试我的第一次 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 个字节数组。

现在我通过我的主要 Activity 将它发送到第二个 Activity :

            //Inside the main activity
Intent i = new Intent(MainActivity.this, DisplayActivity.class);
i.putExtra("element", (Parcelable)adapter.getItem(pos));
startActivity(i);

然后,我在第二个 Activity 中收到了 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.

最佳答案

这样试试:

Element obj = new Element();

//set your data here before send

Intent i = new Intent(this, MyActivity.class);
i.putExtra("com.package.Element", obj);

startActivity(i);

然后检索它:

public class MyActivity extends Activity {

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

Bundle b = getIntent().getExtras();
Element obj = b.getParcelable("com.package.Element");
}

}

关于android - Parcelable 传输失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20312611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com