Kalpesh Kalpesh - 4 months ago 9
Java Question

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

}
}
);

Answer

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));
            }
        }
    );
Comments