0
爲了在新活動中傳遞我的2D陣列,我提出了包裝它並實現接口的方法。不幸的是,當我使用Intent.getParcelableExtra
時,我得到了java.lang.NullPointerException
,這意味着我當然不會實現接口權限。下面是我更新代碼爲自定義2D陣列實現Parcelable
public class MazeMapParcelable implements Parcelable
{
private Cell[][] mazeMap;
public MazeMapParcelable(Cell[][] mazeMap)
{
this.mazeMap = mazeMap;
}
public Cell[][] getMazeMap()
{
return this.mazeMap;
}
public static final Parcelable.Creator<MazeMapParcelable> CREATOR
= new Creator<MazeMapParcelable>() {
public MazeMapParcelable createFromParcel(Parcel in)
{
return new MazeMapParcelable(in);
}
public MazeMapParcelable[] newArray(int size)
{
return new MazeMapParcelable[size];
}
};
public void writeToParcel(Parcel dest, int flags)
{
int width = mazeMap.length;
dest.writeInt(width);
int height = mazeMap[1].length;
dest.writeInt(height);
for(int i=0;i<width;i++)
{
for(int j=0;j<height;j++)
{
dest.writeInt(mazeMap[i][j].getCordX());
dest.writeInt(mazeMap[i][j].getCordY());
dest.writeByte((byte) (mazeMap[i][j].getNorthWall() ? 1 : 0));
dest.writeByte((byte) (mazeMap[i][j].getSouthWall() ? 1 : 0));
dest.writeByte((byte) (mazeMap[i][j].getEastWall() ? 1 : 0));
dest.writeByte((byte) (mazeMap[i][j].getWestWall() ? 1 : 0));
}
}
}
public int describeContents()
{
return 0;
}
public MazeMapParcelable[] newArray(int size)
{
return new MazeMapParcelable[size];
}
private MazeMapParcelable(Parcel in)
{
int width = in.readInt();
int height = in.readInt();
Cell[][] recreatedMazeMap = new Cell[width][height];
for(int i=0;i<width;i++)
{
for(int j=0;j<height;j++)
{
int cordX = in.readInt();
int cordY = in.readInt();
boolean northWall = in.readByte() != 0;
boolean southWall = in.readByte() != 0;
boolean westWall = in.readByte() != 0;
boolean eastWall = in.readByte() != 0;
Cell currCell = new Cell(cordX,cordY,northWall,southWall,westWall,eastWall);
recreatedMazeMap[i][j] = currCell;
}
}
mazeMap = recreatedMazeMap;
}
請注意,我的手機類成員分別是:
protected int x;
protected int y;
private boolean northWall;
private boolean southWall;
private boolean westWall;
private boolean eastWall;
private boolean bomb;
private boolean deadEnd;
更新我不再獲得空指針異常,但我的數據不正確寫入,因爲他們應該。 (parceableMazeMap[0][0] != originalMazeMap[0][0]
)
我發佈我的代碼在更新提到你的建議(如果我理解正確)。我不斷得到nullPointerException我認爲 – 2014-11-24 20:08:54
擴展了一下。 – 2014-11-24 20:13:32
我按照你的指示,但仍然有相同的問題(我根據你的指示更新了我的代碼)。我錯過了什麼嗎? – 2014-11-24 20:41:01