Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android The Solution

If I declare ct variable inside the view method why The app only adds one to the counter then do nothing??

Something like this :

public void onClick(View v) { int i=0;

            i++;
            text.setText(i + "");
        }

2 Answers

If you declare your counter variable inside the onClick() method, what happens is, everytime you click on the button, you call onClick() and:

  • the counter is set to 0 (counter = 0)
  • the counter increases by 1 (counter++), so counter = 1
  • the text on the button is set to the counter value, so "1" When you next click and call onClick() again, the whole thing repeats, starting with resetting the counter to 0. So it never increases any further.

The thing is you do not see the counter reset to 0 first, so you think nothing is happening. But if you set a log right after you initialise your counter variable, and another log right after counter++, like this

public void onClick(View v) {
    int counter = 0;
    Log.i(TAG, "This is the counter value: " + counter);
    counter++;
    Log.i(TAG, "This is the counter value: " + counter);
    textView.setText(Integer.toString(counter));
}

(If you're not familiar with logging, you will need to also declare a TAG variable at the top of your class, like this:

private static final String TAG = MainActivity.class.getSimpleName();

)

each time you click on the button, in Android Studio Logcat, you will see the counter variable is set to 0 first, then to 1.

For example, if I click on the button twice, the Logcat will show:

(...) D/MainActivity: This is the counter value: 0

(...) D/MainActivity: This is the counter value: 1

(...) D/MainActivity: This is the counter value: 0

(...) D/MainActivity: This is the counter value: 1

So for the counter value to increase everytime you click, you want to declare your variable outside the scope of the onClick() method, as it's done in the video.

Hope that helps.

Nataly Rifold
Nataly Rifold
12,431 Points

Similar but different question, if I put the int variable in the onCreate it should be ok. So why should I put it after the MainActivity class?