So, I have created a java class to implement onClickListener and inside this class I have written the onClick public method. Outside of this method, I have created an int object and I want to modify this object inside the onClick method. I have researched a lot by also checking other similar SO questions and I have tried many things, like creating the object as a public int, or making it a private int and have another method to change it and then call this method inside onClick. However, nothing seems to work.
The code shown below has the int object created as a private int and named turn. To change it inside onClick, I have first created a public method named changeTurn that modifies it and then I call this method inside onClick.
public class TicTacToe implements View.OnClickListener { Button buttons[] = new Button[9]; TextView result; public TicTacToe(Button[] buttonList, TextView text) { buttons = buttonList; result = text; } //public void private int turn = 1; // The object that needs to be modified in onCLick @Override public void onClick(View v) { Button b = (Button) v; if((((Button) v).getText() != "X") && (((Button) v).getText() != "O")) { if(this.turn == 1) { b.setText("X"); changeTurn(); // ***Should change the value of turn*** result.setText("Turn is: " + this.turn); } if(this.turn == 2) { b.setText("O"); changeTurn(); // ***Should change the value of turn*** result.setText("Turn is: " + turn); } } } public void changeTurn() { if(this.turn == 1) { this.turn = 2; } if(this.turn == 2) { this.turn = 1; } } } From what I've tried, the program goes only inside the first if every time I click any of my 9 buttons, whose setOnClickListeners are connected to this onClick method. Also, the value of turn is always 1 when I print it out, which basically means that its value is not changed by changeTurn inside the onClick method.
General info on the application: I'm trying to make a tic-tac-toe game in a 3x3 grid with 9 buttons. Since there would be 2 players, I'm trying to use this turn integer to keep track of whose turn it is to press a button. If turn is 1, the button's text gets changed to X and if turn is 2, it changes to O. Right now, every time I press a button, it always changes to X.
I would really appreciate any help or ideas.