Let's try something. We want a "plus" button on the screen, and each time it's pressed I want to print numbers in increasing order, starting with 1. So it prints 1 the first time, 2 the second time, etc. Go ahead and give it a go and come back when you have tried.

Try: Try to build the above app, and come back here if/when stuck.

Back? When trying to find the solution to the problem, you might have tried to write something like this:

public void buttonClick(View v) {
    int number = 0;
    number = number + 1;
    Log.d("MainActivity", "Your number is " + number);
}

But if you run it, you'll find that it prints 1 again and again. What happened?

Let's walk through the lines of code. Each time you press the button, you create a variable called _number, _and set it to 0. You increase it to 1, print it, and end your block of code. This happens every time you press the button, which is why it never grows past 1.

If you remember the lesson about variable scope, you might realize that the variable number gets destroyed when that block ends. If we want to keep a persistent count in between different button clicks, we need to store the number outside the method. What you want to do is something like this:

public class MainActivity extends AppCompatActivity {

    int number = 0;

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

    public void buttonClick(View v) {
        number = number + 1;
        Log.d("MainActivity", "Your number is " + number);
    }
}

The variable is declared outside the buttonClick method, but inside the MainActivity. This means it doesn't get destroyed when the _buttonClick _block of code ends. It will stay alive as long as we are in MainActivity. Running this now produces the output we expect.

A variable like this, declared in the class (MainActivity) scope rather than the method scope, is an instance variable. A variable created inside of a smaller scope, such as in a method, is often referred to as a local variable. When you want information to persist and live outside of the method, you need to use instance variables. This is especially useful if you need two methods to use the same variable; this is not possible if the variable was local to one of those methods.

Try: Expand the app we just did by adding a "minus" button as well. Clicking that decreases the counter instead. Also go ahead and display the number on the screen rather than the console.

results matching ""

    No results matching ""