Android:如何在Parcelable中使用IntArrays?

时间:2017-11-13 08:17:16

标签: java android parcelable

在我的应用中,我有一个课程CurrentGame,我根据此问题中的示例设置了该课程:Android Class Parcelable with ArrayList

但是,我不知道如何将intArray scoresRnd添加到Parcel Constructor。

例如,当我添加此行时,它会以红色加下划线:

this.scoresRnd = parcel.readArray(null);

...我收到此错误消息“不兼容的类型。必需:Int []。发现:java.lang.Object []”。你能帮我么?谢谢! (另外,请指出我的代码中的任何其他错误)

public class CurrentGame implements Parcelable{
    private int rnd;
    private int[] scoresRnd;
    private ArrayList<int[]> scoreList;

    public CurrentGame(){
        super();
        this.rnd = 0;
        this.scoresRnd = new int[]{0,0,0,0};
        this.scoreList = new ArrayList<>();
    }

    public CurrentGame (Parcel parcel){
        this.scoreList = parcel.readArrayList(null);
        this.rnd = parcel.readInt();
        //WHAT DO I PUT HERE FOR THE INTARRAY???

    }

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        // TODO Auto-generated method stub
        parcel.writeList(this.scoreList);
        parcel.writeInt(this.rnd);
    }

    public static final Creator<CurrentGame> CREATOR = new Creator<CurrentGame>() {

        @Override
        public CurrentGame createFromParcel(Parcel parcel) {
            // TODO Auto-generated method stub
            return new CurrentGame(parcel);
        }

        @Override
        public CurrentGame[] newArray(int i) {
            // TODO Auto-generated method stub
            return new CurrentGame[i];
        }
    };

    public void expandList(int[] scoresRnd){
        scoreList.add(scoresRnd);
    }

    public void setRound(int rnd){
        this.rnd=rnd;
    }

    public int getRound(){
        return rnd;
    }

    public ArrayList<int[]> getScoreList(){
        return scoreList;
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(this.rnd);
    dest.writeIntArray(this.scoresRnd);
    dest.writeList(this.scoreList);
}

public s() {
}

protected s(Parcel in) {
    this.rnd = in.readInt();
    this.scoresRnd = in.createIntArray();
    this.scoreList = new ArrayList<int[]>();
    in.readList(this.scoreList, int[].class.getClassLoader());
}

public static final Parcelable.Creator<s> CREATOR = new Parcelable.Creator<s>() {
    @Override
    public s createFromParcel(Parcel source) {
        return new s(source);
    }

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