I have validation for editText
. If the editText
field is empty it should fail validation and stop the user moving on to another Activity
,
You can also try this:
if ( ( userName.getText().toString().trim().equals("")) )
{
Toast.makeText(getApplicationContext(), "User name is empty", Toast.LENGTH_SHORT).show();
}
else
{
Intent i = new Intent(getApplicationContext(), Login.class);
startActivity(i);
}
Try this:
bt.setOnClickListener(new OnClickListener() {
public void onClick(View arg0)
{
String str=et.getText().toString();
if(str.equalsIgnoreCase(""))
{
et.setHint("please enter username");//it gives user to hint
et.setError("please enter username");//it gives user to info message //use any one //
}
else
{
Intent in=new Intent(getApplicationContext(),second.class);
startActivity(in);
}
}
});
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);
}
I know this is an old post, but I needed similar functionality in my application, so I deciced to develop a simple but powerful validator for ease of re-use.
link for github repo It's super easy to use.
validateViewFields
method and pass the list of viewscode example for Activity:
public class AddContractActivity extends AppCompatActivity {
TextView contractDescriptionTextView;
TextView totalAmountTextView;
List<View> fieldsToBeValidated;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contract);
contractDescriptionTextView = findViewById(R.id.contractDescriptionEditText);
totalAmountTextView = findViewById(R.id.totalAmountText);
fieldsToBeValidated = new ArrayList<>(Arrays.asList(
contractDescriptionTextView,
totalAmountTextView));
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!UIValidator.validateViewFields(fieldsToBeValidated, true)) {
Toast.makeText(AddContractActivity.this, "Missing Fields", Toast.LENGTH_SHORT).show();
mainScrollView.post(new Runnable() {
@Override
public void run() {
mainScrollView.smoothScrollTo(0, 0);
}
});
return;
}
}
});
}
}
Better to test empty textField using If condition for all required or special validation cases and setError to focus.
If(txtName.getText().toString().trim().equals(""))
{
//Your message or any other validation
}
I understand it's an old question but may this helps, you can use .isEmpty() instead of .equals()
if( userName.getText().toString().isEmpty()){
/**
* 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);
}