-2

I am new to android and I'm having trouble figuring out how to properly code saving a current game to continue where I left off due to an orientation switch or pressing the home button and returning to the app. I have read about preferences and onSaveInstanceState but, I am having a tough time setting it up properly to work with my Tic-Tac-Toe application. Can someone please help me set this up and explain the process? Thanks in advance.

public class MainActivity extends Activity implements View.OnClickListener {

    private Button TopLeft;
    private Button TopCenter;
    private Button TopRight;
    private Button CenterLeft;
    private Button Center;
    private Button CenterRight;
    private Button BottomLeft;
    private Button BottomCenter;
    private Button BottomRight;
    private Button newGameButton;
    private Button gameGrid[][] = new Button[3][3];
    private TextView displayOut;
    private Random ran = new Random();
    private int count = 9;
    private View v;
    private boolean p = false;
    private boolean c = false;

    // define the SharedPreferences object
    private SharedPreferences savedValues;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Get references to the widgets
        gameGrid[0][0] = (Button) findViewById(R.id.TopLeft);
        gameGrid[0][1] = (Button) findViewById(R.id.TopCenter);
        gameGrid[0][2] = (Button) findViewById(R.id.TopRight);
        gameGrid[1][0] = (Button) findViewById(R.id.CenterLeft);
        gameGrid[1][1] = (Button) findViewById(R.id.Center);
        gameGrid[1][2] = (Button) findViewById(R.id.CenterRight);
        gameGrid[2][0] = (Button) findViewById(R.id.BottomLeft);
        gameGrid[2][1] = (Button) findViewById(R.id.BottomCenter);
        gameGrid[2][2] = (Button) findViewById(R.id.BottomRight);
        newGameButton = (Button) findViewById(R.id.NewGame);
        displayOut = (TextView) findViewById(R.id.DisplayOut);

        // set each button to listen for click
        for (int x = 0; x < gameGrid.length; x++) {
            for (int y = 0; y < gameGrid[x].length; y++) {
                gameGrid[x][y].setOnClickListener(this);
            }
            newGameButton.setOnClickListener(this);
            displayOut.setText("It's Player X's turn.");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void onClick(View v) {
        boolean check = false;
        switch (v.getId())
        {
            case R.id.NewGame:
                newGame();
                break;
            default:
            {
                playerTurn(v);
            }
        }
    }

    private void newGame() {
        for (int x = 0; x < gameGrid.length; x++)
        {
            for (int y = 0; y < gameGrid[x].length; y++)
            {
                gameGrid[x][y].setText("");
                gameGrid[x][y].setClickable(true);
                displayOut.setText("It's Player X's turn.");
            }
        }
        count = 9;
    }

    private void playerTurn(View v) {

        for (int x = 0; x < gameGrid.length; x++)
        {
            for (int y = 0; y < gameGrid[x].length; y++)
            {
                if(gameGrid[x][y].getText() == "O")
                {
                    gameGrid[x][y].setClickable(false);
                }
                if(gameGrid[x][y].getText()== "X")
                {
                    gameGrid[x][y].setClickable(false);
                }
                else
                {
                    gameGrid[x][y].setEnabled(true);
                }
            }
        }
        Button b = (Button) v;

        b.setText("X");

        p = checkWinner();
        count--;
        if(p == true)
        {
            displayOut.setText("Congrats Player X wins!");
            endGame();
            return;
        }
        if(count ==0 && p == false)
        {
            displayOut.setText("Sorry, you tied");
            endGame();
            return;
        }
        else
            displayOut.setText("It's the computer's turn.");
            computerTurn();
    }

    private void computerTurn() {


        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                if (count == 0) {
                    displayOut.setText("Game Ends");
                    return;
                }
//starts here
                try {
                    //check to see if win vertically
                    for (int i = 0; i < 2; i++) {

                        if (gameGrid[0][i].getText() == gameGrid[1][i].getText() &&
                                gameGrid[0][i].getText() == "O") {

                            if (gameGrid[2][i].getText() == "") {
                                gameGrid[2][i].setText("O");


                                return;
                            }

                        }
                    }
                    for (int i = 0; i < 2; i++) {

                        if (gameGrid[2][i].getText() == gameGrid[1][i].getText() &&
                                gameGrid[2][i].getText() == "O") {

                            if (gameGrid[0][i].getText() == "") {
                                gameGrid[0][i].setText("O");


                                return;
                            }

                        }
                    }
                    for (int i = 0; i < 2; i++) {
                        if (gameGrid[2][i].getText() == gameGrid[0][i].getText() &&
                                gameGrid[2][i].getText() == "O") {
                            if (gameGrid[1][i].getText() == "") {
                                gameGrid[1][i].setText("O");


                                return;
                            }
                        }
                    }
                    //check to see if win horizontally
                    for (int i = 0; i < 2; i++) {

                        if (gameGrid[i][0].getText() == gameGrid[i][1].getText()
                                && gameGrid[i][0].getText() == "O") {

                            if (gameGrid[i][2].getText() == "") {
                                gameGrid[i][2].setText("O");


                                return;
                            }

                        }

                    }

                    for (int i = 0; i < 2; i++) {

                        if (gameGrid[i][2].getText() == gameGrid[i][1].getText() &&
                                gameGrid[i][2].getText() == "O") {

                            if (gameGrid[i][0].getText() == "") {
                                gameGrid[i][0].setText("O");


                                return;
                            }

                        }

                    }
                    for (int i = 0; i < 2; i++) {
                        if (gameGrid[i][0].getText() == gameGrid[i][2].getText() &&
                                gameGrid[i][0].getText() == "O") {
                            if (gameGrid[i][1].getText() == "") {
                                gameGrid[i][1].setText("O");


                                return;
                            }
                        }
                    }
                    // check if you can take a win diagonally


                    if (gameGrid[0][0].getText() == gameGrid[1][1].getText()
                            && gameGrid[0][0].getText() == "O") {

                        if (gameGrid[2][2].getText() == "") {
                            gameGrid[2][2].setText("O");


                            return;
                        }
                    }

                    if (gameGrid[2][2].getText() == gameGrid[1][1].getText()
                            && gameGrid[2][2].getText() == "O") {

                        if (gameGrid[0][0].getText() == "") {
                            gameGrid[0][0].setText("O");


                            return;
                        }
                    }
                    if (gameGrid[2][2].getText() == gameGrid[0][0].getText() &&
                            gameGrid[2][2].getText() == "O") {
                        if (gameGrid[1][1].getText() == "") {
                            gameGrid[1][1].setText("O");


                            return;
                        }
                    }

                    if (gameGrid[0][2].getText() == gameGrid[1][1].getText()
                            && gameGrid[0][2].getText() == "O") {

                        if (gameGrid[2][0].getText() == "") {
                            gameGrid[2][0].setText("O");


                            return;
                        }
                    }

                    if (gameGrid[2][0].getText() == gameGrid[1][1].getText()
                            && gameGrid[2][0].getText() == "O") {

                        if (gameGrid[0][2].getText() == "") {
                            gameGrid[0][2].setText("O");


                            return;
                        }
                    }
                    if (gameGrid[2][0].getText() == gameGrid[0][2].getText() &&
                            gameGrid[2][0].getText() == "O") {
                        if (gameGrid[1][1].getText() == "") {
                            gameGrid[1][1].setText("O");


                            return;
                        }
                    }

                    // BLOCKS!!!! //

                    // check if you can block a win vertically
                    for (int i = 0; i < 2; i++) {

                        if (gameGrid[0][i].getText() == gameGrid[1][i].getText()
                                && gameGrid[0][i].getText() == "X") {
                            if (gameGrid[2][i].getText() == "") {
                                gameGrid[2][i].setText("O");

                                return;
                            }

                        }

                    }

                    for (int i = 0; i < 2; i++) {

                        if (gameGrid[2][i].getText() == gameGrid[1][i].getText()
                                && gameGrid[1][i].getText() == "X") {

                            if (gameGrid[0][i].getText() == "") {
                                gameGrid[0][i].setText("O");

                                return;
                            }

                        }

                    }
                    for (int i = 0; i < 2; i++) {

                        if (gameGrid[2][i].getText() == gameGrid[0][i].getText()
                                && gameGrid[0][i].getText() == "X") {

                            if (gameGrid[1][i].getText() == "") {
                                gameGrid[1][i].setText("O");

                                return;
                            }

                        }

                    }


                    // check if you can block a win horizontally
                    for (int i = 0; i < 2; i++) {

                        if (gameGrid[i][0].getText() == gameGrid[i][1].getText()
                                && gameGrid[i][0].getText() == "X") {

                            if (gameGrid[i][2].getText() == "") {
                                gameGrid[i][2].setText("O");

                                return;
                            }

                        }

                    }

                    for (int i = 0; i < 2; i++) {

                        if (gameGrid[i][2].getText() == gameGrid[i][1].getText()
                                && gameGrid[i][2].getText() == "X") {

                            if (gameGrid[i][0].getText() == "") {
                                gameGrid[i][0].setText("O");

                                return;
                            }

                        }

                    }
                    for (int i = 0; i < 2; i++) {

                        if (gameGrid[i][2].getText() == gameGrid[i][0].getText()
                                && gameGrid[i][0].getText() == "X") {

                            if (gameGrid[i][1].getText() == "") {
                                gameGrid[i][1].setText("O");

                                return;
                            }

                        }

                    }


                    // check if you can block a win diagonally


                    if (gameGrid[0][0].getText() == gameGrid[1][1].getText()
                            && gameGrid[0][0].getText() == "X") {

                        if (gameGrid[2][2].getText() == "") {
                            gameGrid[2][2].setText("O");

                            return;
                        }
                    }

                    if (gameGrid[2][2].getText() == gameGrid[1][1].getText()
                            && gameGrid[2][2].getText() == "X") {

                        if (gameGrid[0][0].getText() == "") {
                            gameGrid[0][0].setText("O");

                            return;
                        }
                    }


                    if (gameGrid[0][2].getText() == gameGrid[1][1].getText()
                            && gameGrid[0][2].getText() == "X") {

                        if (gameGrid[2][0].getText() == "") {
                            gameGrid[2][0].setText("O");

                            return;
                        }
                    }

                    if (gameGrid[2][0].getText() == gameGrid[1][1].getText()
                            && gameGrid[2][0].getText() == "X") {

                        if (gameGrid[0][2].getText() == "") {
                            gameGrid[0][2].setText("O");

                            return;
                        }
                    }
                    if (gameGrid[2][0].getText() == gameGrid[0][2].getText() &&
                            gameGrid[2][0].getText() == "X") {
                        if (gameGrid[1][1].getText() == "") {
                            gameGrid[1][1].setText("O");

                            return;
                        }
                    }
                    if (gameGrid[0][2].getText() == gameGrid[2][0].getText() &&
                            gameGrid[0][2].getText() == "X") {
                        if (gameGrid[1][1].getText() == "") {
                            gameGrid[1][1].setText("O");

                            return;
                        }
                    }
                    if (gameGrid[0][0].getText() == gameGrid[2][2].getText() &&
                            gameGrid[0][0].getText() == "X") {
                        if (gameGrid[1][1].getText() == "") {
                            gameGrid[1][1].setText("O");

                            return;
                        }
                    }
                    if (gameGrid[2][2].getText() == gameGrid[0][0].getText() &&
                            gameGrid[2][2].getText() == "X") {
                        if (gameGrid[1][1].getText() == "") {
                            gameGrid[1][1].setText("O");

                            return;
                        }
                    }

                    // make random move if above rules dont apply
                    ArrayList random = new ArrayList();
                    random.add("A");
                    random.add("B");
                    random.add("C");
                    random.add("D");
                    random.add("E");
                    random.add("F");
                    random.add("G");
                    random.add("H");
                    random.add("I");
                    String a = "";
                    for (int x = 0; x < gameGrid.length; x++) {
                        for (int y = 0; y < gameGrid[x].length; y++) {
                            if (gameGrid[x][y].getText() == "X" || gameGrid[x][y].getText() == "O") {
                                String z = x + "," + y;

                                if (z.equals("0,0")) {
                                    a = "A";

                                } else if (z.equals("0,1")) {
                                    a = "B";

                                } else if (z.equals("0,2")) {
                                    a = "C";

                                } else if (z.equals("1,0")) {
                                    a = "D";

                                } else if (z.equals("1,1")) {
                                    a = "E";

                                } else if (z.equals("1,2")) {
                                    a = "F";

                                } else if (z.equals("2,0")) {
                                    a = "G";

                                } else if (z.equals("2,1")) {
                                    a = "H";

                                } else if (z.equals("2,2")) {
                                    a = "I";

                                } else {
                                    displayOut.setText("Error in switch 1");
                                }
                                for (int i = 0; i < random.size(); i++) {
                                    String b = (String) random.get(i);
                                    if (b == a) {
                                        random.remove(a);
                                    }
                                }
                            }
                        }
                    }
                    ArrayList nRand = new ArrayList();
                    nRand = (ArrayList) random.clone();
                    if (nRand.size() <= 0) {
                        displayOut.setText("Game ends");
                        endGame();
                        return;
                    }
                    int index = ran.nextInt(nRand.size());
                    String num = (String) nRand.get(index);

                    if (num.equals("A")) {
                        gameGrid[0][0].setText("O");
                        gameGrid[0][0].setClickable(false);

                    } else if (num.equals("B")) {
                        gameGrid[0][1].setText("O");
                        gameGrid[0][1].setClickable(false);

                    } else if (num.equals("C")) {
                        gameGrid[0][2].setText("O");
                        gameGrid[0][2].setClickable(false);

                    } else if (num.equals("D")) {
                        gameGrid[1][0].setText("O");
                        gameGrid[1][0].setClickable(false);

                    } else if (num.equals("E")) {
                        gameGrid[1][1].setText("O");
                        gameGrid[1][1].setClickable(false);

                    } else if (num.equals("F")) {
                        gameGrid[1][2].setText("O");
                        gameGrid[1][2].setClickable(false);

                    } else if (num.equals("G")) {
                        gameGrid[2][0].setText("O");
                        gameGrid[2][0].setClickable(false);

                    } else if (num.equals("H")) {
                        gameGrid[2][1].setText("O");
                        gameGrid[2][1].setClickable(false);

                    } else if (num.equals("I")) {
                        gameGrid[2][2].setText("O");
                        gameGrid[2][2].setClickable(false);

                    } else {
                        displayOut.setText("Error in switch2");
                    }
                } finally {
//ends here
                    c = checkWinner();
                    count--;
                    if (c == true) {
                        displayOut.setText("Sorry, computer wins");
                        endGame();
                    }
                    if (c == false && count == 0) {
                        displayOut.setText("Sorry, game ends in a tie");
                        endGame();
                    }
                    for (int x = 0; x < gameGrid.length; x++) {
                        for (int y = 0; y < gameGrid[x].length; y++) {
                            if (gameGrid[x][y].getText() == "X") {
                                gameGrid[x][y].setClickable(false);
                            }
                            if (gameGrid[x][y].getText() == "O") {
                                gameGrid[x][y].setClickable(false);
                            }
                        }
                    }
                    displayOut.setText("It's Player X's turn.");
                }
            }
        }, 2000);
    }

    private boolean checkWinner() {

        for (int i = 0; i < gameGrid.length; i++) {

            //vertical win
            if (gameGrid[i][0].getText()==gameGrid[i][1].getText() &&
                    gameGrid[i][1].getText()==gameGrid[i][2].getText() &&
                    gameGrid[i][1].getText()!= "")
            {

                return true;
            }
            //horizontal win(may need its own for loop)
            if (gameGrid[0][i].getText()==gameGrid[1][i].getText() &&
                    gameGrid[1][i].getText()==gameGrid[2][i].getText()
                    && gameGrid[1][i].getText() != "")
            {

                return true;
            }

        }
        //diagonal win
        if ( gameGrid[1][1].getText()==gameGrid[0][0].getText() &&
                gameGrid[1][1].getText()==gameGrid[2][2].getText()
                && gameGrid[1][1].getText() != ""||

                gameGrid[2][0].getText()==gameGrid[1][1].getText()&&
                        gameGrid[1][1].getText()==gameGrid[0][2].getText()
                        &&gameGrid[1][1].getText()!="")
        {

            return true;
        }

        else {
            return false;
        }
    }

    public void endGame() {
        for (int x = 0; x < gameGrid.length; x++)
        {
            for (int y = 0; y < gameGrid[x].length; y++)
            {
                gameGrid[x][y].setClickable(false);
            }
        }
    }

}
  • Hi and welcome to Stack Overflow, please take a time to go through the [welcome tour](https://stackoverflow.com/tour) to know your way around here (and also to earn your first badge), read how to create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and also check [How to Ask Good Questions](https://stackoverflow.com/help/how-to-ask) so you increase your chances to get feedback and useful answers. You are posting too much code, so not many users will be interested on reading it all. – DarkCygnus Jul 03 '17 at 16:02

1 Answers1

0

First of all, try to search because there are a lot of post in which people ask something like you.

I suggest you to see the activity lifecycle https://developer.android.com/guide/components/activities/activity-lifecycle.html when you want to save information about something in your activity, you have to call onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy() depends on what the users done (closing, changing app, etc)

if you see the example in the page above, this is exactly what you want. For example in the onCreate():

// recovering the instance state
    if (savedInstanceState != null) {
        mGameState = savedInstanceState.getString(GAME_STATE_KEY);
    }

So you should save the state in onDestroy() :

// invoked when the activity may be temporarily destroyed, save the instance state here
@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putString(GAME_STATE_KEY, mGameState);
    outState.putString(TEXT_VIEW_KEY, mTextView.getText());

    // call superclass to save any view hierarchy
    super.onSaveInstanceState(outState);
}

In your case you should save the gamegrid.

Other way is to Override the onSaveInstanceState(Bundle savedInstanceState) and onRestoreInstanceState(Bundle savedInstanceState) like Reto Meier said Saving Android Activity state using Save Instance State

MatiRC
  • 189
  • 1
  • 3
  • 13