简体   繁体   中英

How to get data from multiple editText and show in textView if one or more is empty in Android Studio?

In my app there are two EditText named name and age , a TextView named showData and a Button. Basically what I want to do is when a user enters the data in the EditText and clicks the Button the TextView will show the output like this

My name is name
I'm age years old

So for doing this I used If Else inside a setOnClickListener and wrote the code like this,


if (name.isEmpty() && age.isEmpty()) {
    showData.setText(null);
}


else if (age.isEmpty()) {
    showData.setText("My name is " + name);
}

else if (name.isEmpty()) {
    showData.setText("I'm " + age + " years old");
}

else{
    showData.setText("My name is " + name + 
                     "\n I'm " + age + " years old");
}

I'm a beginner in both Java and Android Studio so confused about things there. It would be great if you tell me how to make the app work in standard programming with fewer codes. I mean if and editText is empty the textView won't show any data related to it.

EG: If the user inputs only the name textView will show My name is name only. Or if the user inputs only the age textView will show I'm age years old only. Or if user gives both the textView will show both

Probably this would be appropriate solution in Java (hopefully I did not code a typo, as I am typing directly in the SO pane):

StringBuilder sb = new StringBuilder();
if (!age.isEmpty()) {
    sb.append("My name is " + name);
}

if (!name.isEmpty()) {
  if (sb.length() != 0) {
    sb.append("\n");
  }
  sb.append("I'm " + age + " years old");
}

showData.setText(sb.toString());

By the way, if you were using Kotlin this would have been sooo much nicer.

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