I have validation for editText
. If the editText
field is empty it should fail validation and stop the user moving on to another Activity
, as a value is required. How to do it? I know this is a basic question, but I can't figure out how to do this.
My code:
btninsert = (Button)findViewById(R.id.btn_insert);
btninsert.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
insertValues();
EditText userName = (EditText) findViewById(R.id.editText1);
if( userName.getText().toString().length() == 0 )
userName.setError( "First name is required!" );
Intent i = new Intent(getApplicationContext(), Login.class);
startActivity(i);
}
});
When this Button
is clicked the user is redirect to next screen, but I need that if validation fails they stay on the current Activity
, and only when validation is successful (i.e. a value has been entered) they go to the next Activity
.
I understand it's an old question but may this helps, you can use .isEmpty() instead of .equals()
It's easy...check if your EditText is empty as in below example below.
I faced a similiar problem. In my case, I had a lot of Edittexts to verify, some them was child of another layouts. Tip: all views must be in same root view. So, to be simple:
Try this:
Better to test empty textField using If condition for all required or special validation cases and setError to focus.
You can also try this: