Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement with booleans android

I have been having a problem with a Boolean in an if statement all day and it is really starting to irritate me now!! I have looked at other Android threads on here and the solutions just don't seem t work.

My code started off like this:

public class MainActivity extends Activity 
{
public static boolean isSignedIn = false;       

public final static String USERNAME_MESSAGE = "com.example.libnoise.MESSAGE";
Button btnSignIn;

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


    btnSignIn = (Button) findViewById(R.id.btnSignIn);
    Intent intent = getIntent();
    String message = intent.getStringExtra(PlayZone.USERNAME_MESSAGE); 

    if(isSignedIn == false))
    {
   btnSignIn.setText("SignIn");
    }
    else
    {       
         btnSignIn.setText(message);
    }        
}

Then I had a thought that made it's not like other languages and I only need one "=" sign so I had it as this:

    if(isSignedIn = false)
    {
   btnSignIn.setText("SignIn");
    }
    else
    {       
         btnSignIn.setText(message);
    }  

That didn't work and that's when I started looking online, after finding a previous thread on here changed it to the following:

    if("false".equals(isSignedIn))
    {
   btnSignIn.setText("SignIn");
    }
    else
    {       
         btnSignIn.setText(message);
    }  

Now that doesn't look right to me in the first place but hoped it would work and it didn't.

As this is the MainActivity it loads first however since I added all this, the app crashes before it will even load when I take out the if statement it work as expected.

Any ideas?

like image 742
Defterniko Avatar asked Dec 16 '22 14:12

Defterniko


2 Answers

This

if (isSignedIn == false)

is perfectly correct. (You could also write if (!isSignedIn), but that's just a matter of style.)

Note that, since you never change the value of isSignedIn (at least not in the code you have shown us), it will always be false.

like image 155
Heinzi Avatar answered Jan 01 '23 11:01

Heinzi


i think you can simply use

if(!isSignedIn)
{
  btnSignIn.setText("SignIn");
}
else
{       
  btnSignIn.setText(message);
}        

the way you followed is also correct i didn't find any mistake in except you are using extra bracket in condition if(isSignedIn == false))

like image 37
edwin Avatar answered Jan 01 '23 11:01

edwin