Skip to content
Advertisement

Need help outputting “You must enter a name” when nameText is null. With the code I currently have it doesn’t recognize when the nameText is empty

MainActivity

package com.example.greetings_john_sporn;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

EditText nameText;
TextView textView;
Button btn;

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

    nameText = (EditText) findViewById(R.id.nameText);
    textView = (TextView) findViewById(R.id.textGreeting);
    btn = (Button) findViewById(R.id.buttonSayHello);
    nameText.setText("");
}

public void sayHello(View view) {

    if(nameText != null) {
        textView.setText("Hello " + nameText.getText());
        btn.setEnabled(true);
    } else {
        textView.setText("You must enter a name");
        btn.setEnabled(false);
    }

}
}

Need help setting the text to “You must enter a name” when the nameText is null. For some reason even when the nameText field is empty it still outputs “Hello” when it should be outputting “You must enter a name”.

Advertisement

Answer

Probably you need to check if the text of your EditText is null, not the EditText widget itself.

Try changing your condition

if(nameText != null) {

to

if (!TextUtils.isEmpty(nameText.getText())) {
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement