简体   繁体   中英

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 .

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)

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();

You should use :

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

Otherwise it may throw NullPointerException

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();

Try this,

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

You should check Name and StrName if 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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM