3

活动一:

Bundle bundle = new Bundle();
bundle.putSerializable("CustomLevelData",  LevelCreator.LCLevelData);
Intent i = new Intent(LevelCreatorPopout.this, GameView.class);
i.putExtras(bundle);
startActivity(i);

活动二:

LevelData=(int[][]) extras.getSerializable("CustomLevelData");

错误: E/AndroidRuntime(16220): FATAL EXCEPTION: main E/AndroidRuntime(16220): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.powerpoint45.maze/com.powerpoint45.maze.GameView}: java.lang.ClassCastException: java.lang.Object[] cannot be cast to int[][]

我已经搜索但在 2d INT 数组传递中一无所获

4

3 回答 3

2

如果你仍然想坚持使用 Serializable,你必须在第二个活动中打破它并做一个循环。

Bundle dataBundle = getIntent().getExtras();
int[][] levelData = new int[3][3];

Object[] temp = (Object[])dataBundle.getSerializable("CustomLevelData");
if(temp != null){
    levelData = new int[temp.length][];
    for(int i = 0; i < temp.length; i++){
        levelData[i] = (int[])temp[i];
    }
}
于 2013-11-05T04:25:10.433 回答
1

从性能的角度来看,最好使用Parcelable来传递非原始数据,而不是 Serializable。

不确定这是否是最好的主意,但您可以定义一个包含二维数组并实现 Parcelable 的类。然后,您可以使用以下方法从活动中传递该类的实例:

Intent intent = this.getIntent();
// Assume MyClass is the class which contains the 2d-array
intent.putExtra("key", myclassObj); //value being the instance/object of MyClass that you want to pass

您可以使用以下方法在另一个活动中检索它:

Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
MyClass mc = (MyClass)bundle.getParcelable("key"); 
于 2013-11-05T03:52:15.877 回答
0

我做了什么:

上课

package com.powerpoint45.maze;

导入android.os.Parcel;导入android.os.Parcelable;

公共类 SerializableCustomData 实现 Parcelable{

public int[][] ints;

public int[][] getints() {
    return ints;
}

public void setints(int[][] ints) {
    this.ints = ints;
}

public SerializableCustomData() {
    ints = new int[1][1];
}

public SerializableCustomData(Parcel in) {
    ints = (int[][]) in.readSerializable();
}

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

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeSerializable(ints);

}
public static final Parcelable.Creator<SerializableCustomData> CREATOR = new Parcelable.Creator<SerializableCustomData>() {

    @Override
    public SerializableCustomData createFromParcel(Parcel in) {
        return new SerializableCustomData(in);
    }

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

}

设置它并通过它

SerializableCustomData myParcelable = new SerializableCustomData();
            myParcelable.setints(LevelCreator.LCLevelData);

            Intent i = new Intent(LevelCreatorPopout.this, GameView.class);
            i.putExtra("parcel",myParcelable);
            startActivity(i);

抓住它

SerializableCustomData myParcelable = extras.getParcelable("parcel");
            LevelData = myParcelable.getints();
于 2013-11-06T00:24:24.410 回答