1

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));
Zain Merchant
  • 104
  • 1
  • 10

4 Answers4

2

The ideal solution would be to make the variable static and make it the member of the outer class. Making it static means, all the objects of the class will share a single copy of the variable and the value will remain same everywhere.

Declare static int score; in the outer class.

Mathews Mathai
  • 1,707
  • 13
  • 31
1

If you don't want to use static variables, you could declare the score in the outer class (private int score;), then initialize it in the constructor. This will give it the right scope to be accessed!

slothdotpy
  • 84
  • 1
  • 3
0

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

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

You can use MutableInt which as its name indicates is a mutable integer. This class is provided in the apache commons. This way you can keep the variable local and final.

Hope this helps

Youssef Lahoud
  • 529
  • 3
  • 8