I am trying to add empty field validations on EditText
on AlertDialog
. But even after field is empty error message is not getting displayed, instea
This is how to validate input password inside AlertDialog.
Make sure you have created an individual xml layout file for the password which has only one component/view that is EditText
to get the password from the user.
After creating a layout for input password, we will inflate the layout with Dialog as to set our custom view to the AlertDialog.
Inflater inflater = new Inflater(this);
View myPasswordView = inflater.inflate(R.xml.my_custom_password_layout);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Password");
//alertDialogBuilder.setMessage("Enter password to open Application.");
alertDialogBuilder.setView(myPasswordView);
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
// Do not use this place as we are overriding this button later in the cade.
}
}); alertDialogBuilder.setPositiveButton("Cancel",
new DialogInterface.OnClickListener({
@Override
public void onClick(DialogInterface dialog, int which)
{
// Dismiss dialog and close activity if appropriated, do not use this (cancel) button at all.
dialog.dismiss();
}
});
final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
// Overriding the that button here immediatly handle the user's activity.
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Boolean isError = false;
//Do your job here. For example we are checking the input password.
final EditText txtPassword = myPasswordView.findViewById(R.id.txtPassword);
String password = txtPassword.getText().toString().trim();
Boolean isError = true;
// Check password if not empty. You can add another IF statement to do your logic for password validation.
if(password.isEmpty()) {
isError = true;
txtPassword.setError("Password cannot be empty");
}
if(password.equals("1234") {
// You password is correct.
isError = false;
txtPassword.setError(null);
}
if(!isError)
dialog.dismiss();
// Otherwise the dialog will stay open.
}
});