Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing value of variable in android /JAVA

I was trying to make a simple app in which clicking tapb Button increments the variable value of notaps and the reset Button sets it to 0. When I click on tapb it increments the value & clicking reset resets it but when I again click tabp it increments from the previous value.

Eg :

init value of notaps = 0;

I click tabp 3 times and notaps value = 3

I click reset and notaps value = 0

I click tabp 3 times and notaps value = 4

    Button tapb = (Button)findViewById(R.id.tapb);
    Button reset = (Button)findViewById(R.id.reset);


    tapb.setOnClickListener(
            new Button.OnClickListener(){
                int notaps = 0;
                @Override
                public void onClick(View v) {
                    TextView taps = (TextView)findViewById(R.id.taps);
                    notaps++;
                    taps.setText(String.valueOf(notaps));

                }
            }
    );

    reset.setOnClickListener(
            new Button.OnClickListener() {

                @Override
                public void onClick(View v) {
                    TextView taps = (TextView) findViewById(R.id.taps);
                    int notaps=0;
                    taps.setText(String.valueOf(notaps));

                }
            }
    );
like image 699
Kalpesh Avatar asked Aug 01 '26 07:08

Kalpesh


1 Answers

First, you have 2 instances of int named notaps that have nothing to do with each other. Your reset button does not set the right notaps variable.

Here's a snippet that should work.

    private int notaps;

    Button tapb = (Button)findViewById(R.id.tapb);
    Button reset = (Button)findViewById(R.id.reset);
    TextView taps = (TextView)findViewById(R.id.taps);

    tapb.setOnClickListener(
        new Button.OnClickListener(){
            @Override
            public void onClick(View v) {
                notaps++;
                taps.setText(String.valueOf(notaps));
            }
        }
    );

    reset.setOnClickListener(
        new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                notaps = 0;
                taps.setText(String.valueOf(notaps));
            }
        }
    );
like image 92
Tudor Luca Avatar answered Aug 03 '26 23:08

Tudor Luca