skip to Main Content

I am incredibly new to Android Studio and was hoping to get some assistance.
For some reason, this code is only displaying the ("Hi, " +name) portion. I am not sure what I am doing wrong or how to get the ("You must enter a name") portion to show when there is no text that has been inputted. We are needing to incorporate a SayHello() function into this and I am not sure if I am doing it properly…
enter image description here

package com.example.assignment5_2;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {
    EditText nameText;
    TextView textGreeting;
    Button buttonSayHello;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        nameText = (EditText) findViewById(R.id.nameText);
        textGreeting = (TextView) findViewById(R.id.textGreeting);
        buttonSayHello = (Button) findViewById(R.id.buttonSayHello);

        buttonSayHello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SayHello();
            }

            public void SayHello() {
                String name = nameText.getText().toString();
                if (name != null) {
                    textGreeting.setText("Hi, " + name);
                } else {
                    textGreeting.setText("You must enter a name");
                    buttonSayHello.setEnabled(name.isEmpty());
                }

            }
        });
    }
} 

2

Answers


  1. I think I got your problem, in the SayHello you have to change if(name != null) to

    if(!name.trim().equals("")) or if(name.trim().length > 0)

    Hope this helps

    Login or Signup to reply.
  2. Hey I’ve tried your code and I guess I found the issue, please alter your condition as follows:

     public void SayHello() {
                    String name = nameText.getText().toString();
                    if (!name.isEmpty()) {
                        textGreeting.setText("Hi, " + name);
                    } else {
                        textGreeting.setText("You must enter a name");
                    }
    

    It is preferred to use .isEmpty() method to check if the string is empty or not instead of using != null or == null, by altering your condition like I mentioned above your empty EditText check will work too. Check screenshots below for both cases:

    Case where user enters text in edit text
    Case where edit text is empty and user click button

    try this and do let me know if it works !!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search