i have 2 edit Text in my application, 1 button to add the input numbers in the edit Text and 1 text view to display the result. I would like to put a toast message if my edit te
You can try this two function for string empty, not empty or null. It is simple return true or false. It is very use for all projects.
if(isEmpty(edittext.getText().toString())){
// your Toast message if string is empty
}
if(isNotEmpty(edittext.getText().toString())){
// your Toast message if string is not empty
}
public static boolean isEmpty(String str) {
if (str == null)
return true;
else if (str.toString().trim().length() == 0)
return true;
return false;
}
public static boolean isNotEmpty(String str) {
if (str == null)
return false;
else if (str.toString().trim().length() == 0)
return false;
return true;
}
when user clicks button check:
if (editText1.getText().toString().trim().length() <= 0) {
Toast.makeText(MainActivity.this, "It's empty", Toast.LENGTH_SHORT).show();
}
trim it to avoid blank spaces.
Add to your click listener check
Toast toast = Toast.makeText(MainActivity.this, "Your Message", Toast.LENGTH_SHORT);
toast.show();
Your code will be:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText1 = (EditText)findViewById(R.id.editText1);
final EditText editText2 = (EditText)findViewById(R.id.editText2);
Button button1 = (Button)findViewById(R.id.button1);
final TextView textView1 = (TextView)findViewById(R.id.textView1);
textView1.setText(" ");
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(editText1.getText().toString().trim().length() == 0 || editText2.getText().toString().trim().length() == 0) {
Toast.makeText(this,"Edittext is null",Toast.LENGTH_SHORT).show();
}
else {
double edit1 = Double.valueOf(editText1.getText().toString());
double edit2 = Double.valueOf(editText2.getText().toString());
double text = edit1 + edit2;
textView1.setText(String.valueOf(text));
}
});
}
}
To create and show a Toast use this code:
Toast.makeText(this, "Please input number", Toast.LENGTH_LONG).show();
In order to work properly, you should replace this code:
if (editText1.equals("")) {
editText1.setError("please input number");
}
if (editText2.equals("")) {
editText2.setError("please input number");
}
with this:
if (editText1.getText().toString().length() == 0 || editText1.getText().toString().length() == 1) {
Toast.makeText(this, "Please input number", Toast.LENGTH_LONG).show();
}