editText field is required before moving on to another Activity
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);
}
}
});
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);
}
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:
...
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.viewGroup);
checkFieldsRequired(viewGroup);
...
public boolean checkFieldsRequired(ViewGroup viewGroup){
int count = viewGroup.getChildCount();
for (int i = 0; i < count; i++) {
View view = viewGroup.getChildAt(i);
if (view instanceof ViewGroup)
checkFieldsRequired((ViewGroup) view);
else if (view instanceof EditText) {
EditText edittext = (EditText) view;
if (edittext.getText().toString().trim().equals("")) {
edittext.setError("Required!");
}
}
}
return false;
}
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))
}