Android studio saving data that extends Button

304 Views Asked by At

I'm working on a minesweeper game on android studio.What I'm trying to do is to save the state of the game if the user closes the game while playing.I'm having trouble using parcelable on a object that extends Button Like this:

private final Tile[][] mData = new Tile[8][8]; //8x8 grid   
public class Tile extends Button implements Parcelable
{
    private boolean isMine;
    private boolean isFlag;
    private boolean isCovered;
    private int noSurroundingMines;

I know i need to use onSaveInstanceState and use Parcelable

public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putParcelable("test", (Parcelable) mData); <--Error
}        

*Error:Inconvertible types;Cannot Cast GameActivity.Tiles to android.Parcelable

I also know that you can't save 2d array and i'm aware of the work around. I realy want to find out how to save an object that extends button

2

There are 2 best solutions below

0
On

You are not actually using the Parcelable Interface when you are trying to save mData.

What you might want to do is to put the 2d array inside a wrapper that implements Parcelable.

public class Minefield implements Parcelable
{
    private Tile[][] mData;

    public Minefield() {
        mData = new Tile[8][8]
    }
}

Then in your main activity, create an instance of Minefield if there is no saved state:

private final Minefield minefield;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);

    if (savedInstanceState != null) {
        //do stuff with savedInstanceState
    } else {
        minefield = new Minefield();
    }
}
0
On

Why are you trying to cast mData as Parcelable?

savedInstanceState.putParcelable("test", (Parcelable) mData);

Tile[][] mData is a 2 dimensional array and this is not Parcelable itself, but its content would be say myTile=mData[0][1].

savedInstanceState.putParcelable("test", myTile);

Please read more on OOPs concept.