Android将一个2d int数组从一个活动传递到另一个ERROR

时间:2013-11-05 03:40:24

标签: java android arrays 2d

活动1:

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

活动2:

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数组传递

时没有找到任何内容

3 个答案:

答案 0 :(得分: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];
    }
}

答案 1 :(得分:1)

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

不确定这是否是最好的想法,但您可以定义一个包含2d数组并实现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"); 

答案 2 :(得分:0)

我做了什么:

制作课程

package com.powerpoint45.maze;

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

public class 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);

GRAB IT

SerializableCustomData myParcelable = extras.getParcelable("parcel");
            LevelData = myParcelable.getints();