I am trying to add empty field validations on EditText
on AlertDialog
. But even after field is empty error message is not getting displayed, instead AlertDialog
is closing. But if conditions are working well as I'm not able to do post operations if any of the field is empty.
Here is my Java Sample code:
public class TourActivity extends AppCompatActivity {
private LayoutInflater inflater;
private FloatingActionButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tour);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
inflater = TourActivity.this.getLayoutInflater();
View content = inflater.inflate(R.layout.activity_add_new_trip, null);
final EditText editEvent = (EditText) content.findViewById(R.id.edTxt_EventName);
final EditText editStartDate = (EditText) content.findViewById(R.id.edTxt_EventSDate);
AlertDialog.Builder builder = new AlertDialog.Builder(TourActivity.this);
builder.setView(content)
.setTitle("Add Event")
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
editEvent.setError(null);
editStartDate.setError(null);
boolean cancel = false;
View focusView = null;
if (TextUtils.isEmpty(editEvent.getText().toString()))) {
editEvent.setError("Please Enter Event Name.");
return;
}
if (TextUtils.isEmpty(editStartDate.getText().toString())) {
editStartDate.setError("Please Enter Event Start Date.");
focusView = editStartDate;
cancel = true;
}
if (cancel == true) {
Snackbar.make(findViewById(android.R.id.content),
"Event Unsuccessful.", Snackbar.LENGTH_LONG)
.setActionTextColor(Color.RED)
.show();
focusView.requestFocus();
} else {
// Some action here
}
}
})
.setNegativeButton(cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}