Search code examples
javaandroidvariablesbuttonfinal

Variable needs to be declared final


I am trying to have a score variable go up by one every time a button is clicked. The problem is I must declare the score variable outside of the onClick otherwise it will always be set to 0. Also, I cannot declare the variable final because I am modifying the variable. Here is the code.

    int score = 0;

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            score++;

            scoreLabel.setText(String.valueOf(score));

Solution

  • The problem is that the var score is scoped in a method, move that and declare score as a class variable.