How to change variable inside a method

78 Views Asked by At

I'm new at programming android apps. How can I change a variable (bool) inside a button-method (or any method)

Here is just an example:

package com.example.test1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.renderscript.Sampler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button btn1,btn2;
    Boolean player1is = true;
    TextView controllview;
    TextView controllview2;

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

        btn1= findViewById(R.id.button1);
        btn2 = findViewById(R.id.button2);
        controllview=findViewById(R.id.controll1);
        controllview2=findViewById(R.id.controll2);

        if(player1is){
            btn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    player1is = false;
                    controllview.setText(String.valueOf(player1is));
                    Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
                }
            });
        }else {
            btn2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    player1is = true;
                    controllview.setText(String.valueOf(player1is));
                    Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
                }
            });

        }
        controllview2.setText(String.valueOf(player1is));
    }
}

If I run this code, controllview changes but controllview2, which shows the global value of player1is, does not change. I also tried to change the value in a separate method like:

public void changebool(Boolean c) {
    player1is= c;
}

then call it from the onclick-method with the desired value, but it had the same effect.

I know, that I am missing a very basic point here but the examples I found were not satisfying (or I searched the wrong way).

What I plan to do is, that every "player" (in an already working, more complex app - apart from this minor issue) can push the button alternately.

Also tried to use a switch or write and read values to a textview in the corresponding XML.

I want that the two buttons will work alternately. I put it in another way:

  1. Until Button1 is not pressed, Button2 should not work but a klick on Button1 activates Button2. (And of cause the other way) Its for determine turns in another app.
6

There are 6 best solutions below

2
Ribbon Charm On

Use java.util.concurrent.atomic.AtomicBoolean may solve this problem

1
Nifil On

You never update the text of controllview2, you just set it in the onCreate method.

You should change it in your event handlers, maybe create a function for updating the ui when an event happens and it can read it again. Also the event handlers should be assigned regardless of the value of player1is

Anyways the way you assign it is fine and you don't need your changebool method

3
Ticherhaz FreePalestine On

I think I understand what you are trying to implement. But first, try to avoid checking the boolean while doing the event handler. Do something like this instead.

btn1.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
      updateData();
   }
});
       
btn2.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
      updateData();
   }
});

At outside from the method onCreate , you can create a new method to call.

private void updateData(){
   if(player1is){
      player1is = false;
      ontrollview.setText(String.valueOf(player1is));
      Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
   }else {
      player1is = true;
      controllview2.setText(String.valueOf(player1is));
      Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
   }
}
0
Oliver Neumann On

I turned down my problem further. I want to change the value of buttonpressed with a button so I can use it later for an if-statement. So this is where I am right now:

package com.example.publicbool;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    Boolean buttonPressed = false;
    TextView test;

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

        final Button button_a = (Button) findViewById(R.id.p1_btn);
        test = findViewById(R.id.globalview);

        button_a.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "klick", Toast.LENGTH_SHORT).show();
                buttonPressed = true;
            }
        });
        test.setText(String.valueOf(buttonPressed));
    }
}

0
Renzo Sampietro On

In my opinion, it should put

`controlview2.setText(String.valueOf(player1is));` 

in onClick functions.

As mentioned by Nifil, onCreate() callback is called only when the activity is first created (and not by clicking buttons).

I recommend that you consult Google's instructions regarding activity lifecycle

0
Oliver Neumann On

I finally solved this issue. I have to declare the variable inside the oncreate method and do the if-statement inside the onclick method of the buttons. Android Studio then wants me to change the boolean into an array which is fine for me. So the working code is now:

package com.example.publicbool;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

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


        final boolean[] ident = {true};
        Button btn1 = findViewById(R.id.p1_btn);
        Button btn2 = findViewById(R.id.p2_btn);
        
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ident[0]){
                    ident[0] = false;
                    Toast.makeText(MainActivity.this, "links", Toast.LENGTH_SHORT).show();
                }
            }
        });
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ident[0]){
                    ident[0] = true;
                    Toast.makeText(MainActivity.this, "rechts", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }    
}

Now the two buttons work in alternating order.