How can I create a loop in Android programming and how can I increment a variable value after each button click event? I want to preserve value of variable "over" value for each button click.

My code is as follows:

Button btnScore = (Button) findViewById(R.id.ScoreButton);

btnScore.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (RadioButton1.ischecked()){
            int over = 0;
            if (RadioRavi.ischecked()){
                EditText e12 = (EditText)findViewById(R.id.editText12);                        
               over = over + 1; //I want this loop for four times i.e. after four times 

               //button click it should have the value of 4;
               //problem is that when each time when i click button btnScore then it 
               //initializes variable "over" to 0;

               e12.setText(String.valueOf(over));
               //I want when I click button btnScore four times then 
               //variable "over" should contain the value "4".    
               //for each button click the value of over should be increase by 1.   
     }
}

I want the loop continues for each time I click the button. I mean to say that variable "over" value must be preserved between button click.

1 Answers

0
Community On

As I understand you want to increment value on every button click.

So you need something like this.

Button btnScore = (Button) findViewById(R.id.ScoreButton);
EditText e12 = (EditText)findViewById(R.id.editText12);
int over = 0;

btnScore.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (RadioButton1.ischecked()){
            if (RadioRavi.ischecked()){

               //Select one of the solutions :)

               //Solution 1:
               over = over + 1;
               e12.setText(String.valueOf(over));

               //Solution 2:
               over++;
               e12.setText(String.valueOf(over));

               //Solution 3:
               e12.setText(String.valueOf(over++));

     }

}