【发布时间】:2014-11-24 19:23:22
【问题描述】:
为了在新活动中传递我的二维数组,我想出了包装它并实现 Parcelable 接口的方法。不幸的是,当我使用Intent.getParcelableExtra 时,我得到java.lang.NullPointerException,这意味着我肯定没有正确实现接口。下面是我的更新代码
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;
}
请注意,我的 Cell 班级成员是:
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])
【问题讨论】:
标签: android android-intent nullpointerexception parcelable