gpt4 book ai didi

java - Parcelable 协议(protocol)需要一个名为 CREATOR 的 Parcelable.Creator 对象(我确实有 CREATOR)

转载 作者:IT老高 更新时间:2023-10-28 20:32:55 30 4
gpt4 key购买 nike

我正在尝试将 Parcelable 数据从一个 Intent 传递到另一个 Intent ,这是我得到的错误:

08-31 14:12:22.709: E/AndroidRuntime(9931): FATAL EXCEPTION: main
08-31 14:12:22.709: E/AndroidRuntime(9931): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.matejsoftware.cardscoretracker/com.matejsoftware.cardscoretracker.Igra}: android.os.BadParcelableException: Parcelable protocol requires a Parcelable.Creator object called CREATOR on class com.matejsoftware.cardscoretracker.Novaigra$Player

问题是:我确实有 Parcelable.Creator 对象。我将在下面发布整个 Parcelable 代码:

public class Player implements Parcelable{
String name;
int score;
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(score);
}

public Player(Parcel source){
score = source.readInt();
name = source.readString();
}

public Player(int score, String name){
this.score = score;
this.name = name;
}
}

public class MyCreator implements Parcelable.Creator<Player> {

@Override
public Player createFromParcel(Parcel source) {
return new Player(source);
}

@Override
public Player[] newArray(int size) {
return new Player[size];
}

}

CREATOR 有什么问题吗?当我单击按钮开始下一个 Activity 时,应用程序立即崩溃。

这就是我在第二个 Activity 中“检索”Parcelable 数据的方式:

//global variable
ArrayList<Player> playersParceledData;

//This is in onCreate
playersData = getIntent();
playersParceledData = playersData.getParcelableArrayListExtra("parceledData");

另外,这就是我将类对象放入 ParcelableArrayListExtra 的方式:

Player newPlayer = new Player(0, text);
playersParceledData.add(newPlayer);
zacniIgro.putParcelableArrayListExtra("parceledData", playersParceledData);

最佳答案

从 Parcel 读取的顺序与写入的顺序不同。

writeToParcel() 中,您首先放入 String,但在 HeatFriendDetail(Parcel in) 中,您首先读取整数。这不是正确的方式,因为顺序或读/写很重要。

以下是在向 Parcel 写入/读取数据时执行正确顺序的代码(另见 this link):

public class FriendDetail implements Parcelable {

private String full_name;
private int privacy;

public HeatFriendDetail(Parcel in) {
this.full_name = in.readString();
this.privacy = in.readInt();
}

public HeatFriendDetail() {

}

@Override
public void writeToParcel(Parcel dest, int flags) {

dest.writeString(this.full_name);
dest.writeInt(this.privacy);
}

public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public HeatFriendDetail createFromParcel(Parcel in) {
return new HeatFriendDetail(in);
}

public HeatFriendDetail[] newArray(int size) {
return new HeatFriendDetail[size];
}
};

// GETTER SETTER//
}

关于java - Parcelable 协议(protocol)需要一个名为 CREATOR 的 Parcelable.Creator 对象(我确实有 CREATOR),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18548077/

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