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
.
Set the Text of Android EditText If you observe above example we used android:text property to the set required text for EditText control in XML Layout file. Following is another way to set the text of EditText control programmatically in activity file using setText() method. EditText et = (EditText)findViewById(R. id.
We can set editable property of EditText in XML layout but not programatically, but there is no setEditable() method! If EditText is not Enabled [ by setEnabled(false) ] it still Editable!
Advertisements. A EditText is an overlay over TextView that configures itself to be editable. It is the predefined subclass of TextView that includes rich editing capabilities.
It's easy...check if your EditText is empty as in below example below.
if( TextUtils.isEmpty(userName.getText())){ /** * You can Toast a message here that the Username is Empty **/ userName.setError( "First name is required!" ); }else{ Intent i = new Intent(getApplicationContext(), Login.class); startActivity(i); }
Here is a Kotlin version:
userName.takeIf { it.isEmpty() }?.let { userName.error = "First name is required!" } ?: run { startActivity(Intent(applicationContext, this)) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With