Take the 2-minute tour ×

I am trying to do some EditText validation and want to use an AlertDialog when the user inputs something that is illegal.

How can I have an alert dialog pop up and tell the user what is wrong with the input and then after "OK" is pressed just go back to the same view?

I'm waiting until a "confirm" button is pressed to do validation and am already inside a button's onClickListener in an Activity like so:

protected void onCreate(Bundle savedInstanceState) {
    // user adds info to progress screen
    // clicks confirm when done
Button confirmButton = (Button) findViewById(R.id.confirm); 
    confirmButton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View view) {
          // do validation code here
          AlertDialog alert = new AlertDialog.Builder(AddStudentProgress.this).create();
          alert.setMessage("Inputs Can't be Empty");
          alert.setButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // I reall want to go back to the Activity and not really do anything

          if ( (mScoreText.getText().toString().equals("") )) {
          else {
            // validation looks ok, continue

Am I going about this the wrong way? What should I be doing of I want to validate input?

Thanks in advance, Martin

share|improve this question

2 Answers 2

up vote -1 down vote accepted

The following piece will do the trick

alert.setButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
share|improve this answer
but I think I'm still dealing with buttons and such. –  Martin Jun 28 '11 at 10:26

An AlertDialog is not the best way to alert your user of form errors. You can highlight the error on the field itself, with a helpful message:

    mScoreText.setError("Please enter your name");

This way, the user doesn't need to dismiss an alert, and they can see the error in context.

share|improve this answer
Yes, this is much better! –  Azlam Jun 28 '11 at 10:06
Excellent. I like this. Thanks very much. –  Martin Jun 28 '11 at 10:25

Your Answer


