Reputation: 25
I am getting this error and I really can't understand why. The code:
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
boolean b = true;
if(b == true){
tv1.setText("true");
b2.setEnabled(false);
b = false;
} else
if(b == false){
b2.setEnabled(true);
b = true;
tv1.setText("false");
As you can see I'm trying to make when a button is clicked it will check if variable "b" is true or false and then it should do the following code. But it doesn't! It only does the actions for the "if b == true". Can you help me?
Upvotes: 1
Views: 255
Reputation:
From the code that you put up, this is the reason I can think of:
Initially, your b variable is set to true. Hence, it enters the b == true
condition.
But when you set the b==false
"inside" that if, it DOES NOT go to else. The reason is simply because, when you have gone to the "if" statement already, that is the condition for if statement was verified to be true, the computer doesnt need to look for the "else" statement and hence doesn't go into it.
If you would have had two consecutive ifs instead of else, your thing would have worked the way you expect it to be.
Upvotes: 0
Reputation: 7234
The variable 'b' is a local variable within the scope of the method so it is always true when the onClick() method executes. You need to move the variable into the class scope. Like this:
b1.setOnClickListener(new View.OnClickListener() {
boolean b = true;
public void onClick(View arg0) {
if (b) {
tv1.setText("true");
b2.setEnabled(false);
b = false;
} else {
b2.setEnabled(true);
b = true;
tv1.setText("false");
}
}
});
Upvotes: 1
Reputation: 328598
Maybe because b is always true following this statement:
boolean b = true;
Also, b being a boolean, you can simply write:
if (b) {
//
} else {
//
}
This might work as you expect (not tested):
b1.setOnClickListener(new View.OnClickListener() {
private boolean b = true;
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(b){
b2.setEnabled(false);
tv1.setText("true");
} else {
b2.setEnabled(true);
tv1.setText("false");
}
b = !b; //this changes b from true to false and vice versa at each call
}
});
Upvotes: 4
Reputation: 391
you'd want to use the static modifier to keep the state of the variable ( since its state will not be kept when it goes out of scope.) this also means that you'd have to move the variable out to a global scope.
Upvotes: 0
Reputation: 2662
You have to declare the variable b outside your Listener
boolean b = true;
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(b == true){
tv1.setText("true");
b2.setEnabled(false);
b = false;
} else
if(b == false){
b2.setEnabled(true);
b = true;
tv1.setText("false");
Upvotes: 1