1

sorry if this is a low quality question, but still is a question :) here im using a simple in the eyes condition for checking EditText's null Being,

public String theuser=null;
public String thepass=null;

EditText  u=(EditText)findViewById(R.id.inputuser);
this.theuser = u.getText().toString();
EditText p =(EditText)findViewById(R.id.inputpassword);
this.thepass = p.getText().toString();

if ((theuser.equals(null))||(thepass.equals(null))){ 
    Toast.makeText(this,"Username and Password Cant Be Empty!",     
    Toast.LENGTH_SHORT).show();   
}else{
    Log.i("lifemate","did you click me ?!"+theuser+"  "+thepass);
    BusProvider.getInstance().post(SendRequestInfo());
}

but the null check seems to be not working ! i tried .equals(null) and .equals("") too still not working! do guys know why is that ?!

earthmover
  • 4,395
  • 10
  • 43
  • 74
user3694470
  • 143
  • 1
  • 12

6 Answers6

3

Comparison to null should be done using the == operator.

So use if (theuser==null || thepass == null).

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
2

that if ((theuser.equals(null))||(thepass.equals(null))){

must be if ((theuser.equals(""))||(thepassequals(""))){

because getText() returns an empty string if there is no input. It not return null.

Jens
  • 67,715
  • 15
  • 98
  • 113
0

equals null is not applicable for the reference of your String object.

You need to use (mystring != null) to test the nullability.

marshallino16
  • 2,645
  • 15
  • 29
0

replace

if ((theuser.equals(null))||(thepass.equals(null)))

with

if (theuser==null||thepass==null)
Macrosoft-Dev
  • 2,195
  • 1
  • 12
  • 15
0

Equals contract states that:

For any non-null reference value x, x.equals(null) should return false.

But when x is null this would cause a NullPointerException because you are trying to access a method of a null object.

In short use x == null rather than x.equals(null).

But in your case

You are testing the text value from a TextView. I would not expect this to be null, particulary as you call toString() on a CharSequence. So this will be just empty if anything, i.e. you can do this:

if ("".equals(theuser) || "".equals(thepass)) {
Community
  • 1
  • 1
weston
  • 54,145
  • 21
  • 145
  • 203
0

For checking the null in string android provide very good class over there

you just pass your string in

//check while for the null string. 
if(TextUtils.isEmpty("YOUR_STRING")){
 //perform operation. 
}

It will automatically handle NULL as well as EMPTY string.

GovindRathod
  • 867
  • 1
  • 8
  • 22