I have an app with 4 EditText and one button that is supposed to calculate the inputs given
When one of those are left empty then the app crashes
How can I validate to throw an error when a EditText is left empty
You can use TextUtils.isEmpty(stringData)
and it is preferred. For string.isEmpty()
, a null string value will throw a NullPointerException
.
TextUtils
will always return a boolean
value. In code, the former simply calls the equivalent of the other, plus a null check.
EditText myEditText1 = findViewById(R.id.editText1);
EditText myEditText2 = findViewById(R.id.editText2);
EditText myEditText3 = findViewById(R.id.editText3);
EditText myEditText4 = findViewById(R.id.editText4);
String myData1 = myEditText1.getText().toString();
String myData2 = myEditText2.getText().toString();
String myData3 = myEditText3.getText().toString();
String myData4 = myEditText4.getText().toString();
if(!TextUtils.isEmpty(myData1) && !TextUtils.isEmpty(myData2) && !TextUtils.isEmpty(myData3) && !TextUtils.isEmpty(myData4)) {
//use edit text data
} else {
Toast.makeText(this, "Fields value can not be empty",Toast.LENGTH_SHORT).show();
}
When you click the button check if the EditText is empty or not
Try below code
if(editText.getText().toString.length() == 0){
// Display toast
Toast.makeText(getApplicationContext(), "Please enter something !",Toast.LENGTH_LONG).show();
}
Or you can use a library called AwesomeValiation
First you need to link the edit text and button with the id
EditText editText1 = findViewById(R.id.editText1);
EditText editText2 = findViewById(R.id.editText2);
EditText editText3 = findViewById(R.id.editText3);
EditText editText4 = findViewById(R.id.editText4);
Now you can get the value from the editText by using the below code
String data = editText.getText();
For check the null value
if (data.isEmpty ){
Toast.makeText(getApplicationContext(),"the data is "+data,Toast.SHORT_LENGTH).show;
}
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.