Issue
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());
}
}
});
}
}
Solution
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:
try this and do let me know if it works !!
Answered By - D3mon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.