简体   繁体   中英

save the state of the board for orientation

Hi I am a newbie at android and going through a tutorial for tictactoe. I need to save the state of the board so that when I change orientation the board appears with characters intact. Here are the pieces of code - The tries and turns strings are being saved and display but not the X's and O's on the board. I do not have a clue why

MainActivity.java

           mGame = new TicTacToeGame();

       if (savedInstanceState == null) { 
            startNewGame();
            } 
            else { 
             // Restore the game's state                    
            mGame.setBoardState(savedInstanceState.getCharArray("board"));              
            mGameOver = savedInstanceState.getBoolean("mGameOver"); 
            mInfoTextView.setText(savedInstanceState.getCharSequence("info")); 
            mHumanWins = savedInstanceState.getInt("mHumanWins"); 
            mComputerWins = savedInstanceState.getInt("mComputerWins"); 
            mTies = savedInstanceState.getInt("mTies"); 
            mTurn = savedInstanceState.getChar("mTurn"); 
            } 
            displayScores(); 

       }

        @Override
    protected void onSaveInstanceState(Bundle outState) {
     super.onSaveInstanceState(outState);
     outState.putCharArray("board", mGame.getBoardState());
     outState.putBoolean("mGameOver", mGameOver);
     outState.putInt("mHumanWins",Integer.valueOf(mHumanWins));
     outState.putInt("mComputerWins",Integer.valueOf(mComputerWins));
     outState.putInt("mTies", Integer.valueOf(mTies));
     outState.putCharSequence("info", mInfoTextView.getText());
     outState.putChar("mTurn", mTurn);
    }

Here are the methods on the tictactoe game returning the state of the board:

    public char[] getBoardState() {
    return mBoard;
}

public void setBoardState(char[] board) {
    mBoard = board.clone();
}

Thanks in advance for any help.

I think the problem might be in your setBoardGame method. The clone() method returns type "Object", but mBoard is type "char[]" (a character array). Therefore, you need to cast from type Object to type char[]

Try this:

public void setBoardState(char[] board) {
    mBoard = (char[]) board.clone();
}

Try

public char[] getBoardState() {
return mBoard.clone();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM