Java – Change the value of variables in android/JAVA

Change the value of variables in android/JAVA… here is a solution to the problem.

Change the value of variables in android/JAVA

I’m trying to make a simple application where clicking tapb button increases the variable value of notaps, while resetting the button sets it to 0. When I click tabp it increases the value and click reset to reset it, but when I click tabp again it increases from the previous value.

For example:

init value of notaps = 0;

I hit tabp 3 times and notaps value = 3

I hit reset and notaps value = 0

I hit 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));

}
            }
    );

Solution

First, you have 2 int instances named notaps, which are independent of each other. Your reset button does not have the correct notaps variable set.

This is a fragment 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));
            }
        }
    );

Related Problems and Solutions