In order to pass my 2D array in a new activity, I came up with the approach to wrap it and implement the Parcelable interface. Unfortunately, when I use Intent.getParcelableExtra
i get java.lang.NullPointerException
, which means that I am most certainly not implementing the interface right. Below is my Updated code
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;
}
Note that my Cell class members are:
protected int x;
protected int y;
private boolean northWall;
private boolean southWall;
private boolean westWall;
private boolean eastWall;
private boolean bomb;
private boolean deadEnd;
Update I no longer get Null pointer exception, but my data are not written properly as they should. (parceableMazeMap[0][0] != originalMazeMap[0][0]
)