Fino
Fino

Reputation: 1

EditText.getText().toString() crashes on button click

I have the following problem. I want to check my EditText if it contains a value/string on Button click. Here we go:

private EditText Name;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    Name = (EditText)findViewById(R.id.RegisterName);

}

    public void RegisterClick(View v)
{
    String StrName = Name.getText().toString();
    if(StrName != "")
        Toast.makeText(null, "Got My String.", Toast.LENGTH_LONG).show();
}

And I put also this into the layout.xml, its not the whole code

<Button
android:onClick="RegisterClick" />

So now, when I try to debug, the debugger closes after I pass the sequenze where I want to set StrName from the EditText.

Upvotes: 0

Views: 1423

Answers (7)

M Karthik
M Karthik

Reputation: 11

you have to use the below code to compare a string

1.

if(StrName.Matches(""))
 Toast.makeText(getApplicationContext(), "Got My String.", Toast.LENGTH_LONG).show();

2.

if(StrName.compareToIgnoreCase(string))
 Toast.makeText(getApplicationContext(), "Got My String.", Toast.LENGTH_LONG).show();

Upvotes: 1

Tarsem Singh
Tarsem Singh

Reputation: 14199

To compare String use equals() method and instead of null pass cotext in your Toast :-

 if(StrName.equals(""))
    Toast.makeText(getApplicationContext(), "Got My String.", Toast.LENGTH_LONG).show();

Upvotes: 0

Devolus
Devolus

Reputation: 22094

You should check Name and StrNameif they are null. MakeText requires a Context, so it may not be null either.

Additionaly

if(StrName != "")

is not doing what you think, so you should use

if(StrName.equals(""))

but of course this doesn't cause a crash, just wrong behaviour.

Upvotes: 0

No_Rulz
No_Rulz

Reputation: 2719

Try this,

  if(!StrName.equals("") && StrName.length() > 0){
    Toast.makeText(getApplicationContext(), "Got My String.", Toast.LENGTH_LONG).show();
    }

Upvotes: 0

Nermeen
Nermeen

Reputation: 15973

You need to check if the edit text contains null first..

if(Name.getText() == null || Name.getText().toString().equals(""))
     Toast.makeText(context, "Got My String.", Toast.LENGTH_LONG).show();

Upvotes: 0

Abubakkar
Abubakkar

Reputation: 15664

You should use :

if(StrName != null && StrName.length() > 0)

Otherwise it may throw NullPointerException

Upvotes: 0

StErMi
StErMi

Reputation: 5469

Where is it crashing?

I think that is crashing here:

Toast.makeText(null, "Got My String.", Toast.LENGTH_LONG).show();

You cannot pass a null context to makeText. If you are in an activity pass it this otherwise (if you are in a fragment) pass a getActivity()

Also, in Java, NEVER use != or == with strings but ALWAYS s1.equals(s2) (and before it do a null check)

Upvotes: 7

Related Questions