Home > Enterprise >  Need help outputting "You must enter a name" when nameText is null. With the code I curren
Need help outputting "You must enter a name" when nameText is null. With the code I curren

Time:06-13

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".

CodePudding user response:

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())) {
  • Related