I have an EditText
and a Button
.
I want if an EditText
was empty when clicked on my Button
. I want to show message as a toast, like "please enter a number".
I have an EditText
and a Button
.
I want if an EditText
was empty when clicked on my Button
. I want to show message as a toast, like "please enter a number".
You can do something like this:
boolean hasValue = editText.getText().length() > 0;
or
boolean hasValue = !editText.getText().toString().isEmpty();
or to make sure it doesn't contain only spaces:
boolean hasValue = !editText.getText().toString().trim().isEmpty();
The cleanest way to do this is TextUtils.isEmpty(editText.getText())
The reason I say this is the cleanest way is because:
CharSequence
and String
. Which creates an object. editText.getText()
returns Editable
, calling toString()
creates an additional object which is not good. This method will also never return null in my experience.null
and a length
check out of that. If you look at the code for TextUtils.isEmpty()
, it basically checks if the CharSequence
is null
and length is zero.String
s or CharSequence
objects and Editable
is an implementation of CharSequence
.If you want to check the length of the trimmed String. Then use:
TextUtils.isEmpty(editText.getText())
&& TextUtils.getTrimmedLength(editText.getText()) == 0
If you want, you can create your own utility method to do this so you don't have to add such a long condition in your code repeatedly.
I would attached an OnFocusChangeListener
to your EditText
to check the change in value or a TextWatcher
or both depending on how critical your requirement is. If your field had focus and lost it, do your validation with the OnFocusChangeListener
, if your field has focus and the user is typing and delete the content or the content is too short, use TextWatcher
to let them know.
Use this on click of your button:
EditText editText = (EditText) view.findViewById(EditTextID);
if(editText.getText().toString().length()==0) {
Toast alert = Toast.makeText(context, toast_message, Toast.LENGTH_SHORT);
alert.show();
}
In the onClickListener() of the button:
int length = editText.getText().length();
if(length == 0)
{
Toast.makeText(getActivity(), "Please enter a number",Toast.LENGTH_LONG).show();
}
you probably already found your answer, but for the ones who came here hoping to find an answer here is how its done:
you have to make a String object or Int object first then in your button function Click write this:
@Override
public void onClick(View view) {
String numberValue;
numberValue = yourEditText.getText().toString();
if (emailEtValue.matches("")){
Snackbar sbEmptyValue = Snackbar.make(view, "You must enter an Integer Value", Snackbar.LENGTH_LONG);
sbEmptyValue.show();
} else {
//DO THE THING YOU WANT
}
}
you can also use Toast but i prefer Snackbar because its cooler than Toast.