Null Validation on EditText box in Alert Dialog - Android

Posted by LordSnoutimus on Stack Overflow See other posts from Stack Overflow or by LordSnoutimus
Published on 2010-04-05T19:27:36Z Indexed on 2010/04/05 19:33 UTC
Read the original article Hit count: 1478

Filed under:
|
|
|

Hi,

I am trying to add some text validation to an edit text field located within an alert dialog box. It prompts a user to enter in a name.

I want to add some validation so that if what they have entered is blank or null, it does not do anything apart from creating a Toast saying error.

So far I have:

AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Record New Track"); alert.setMessage("Please Name Your Track:"); // Set an EditText view to get user input final EditText trackName = new EditText(this); alert.setView(trackName); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) {

            String textString = trackName.getText().toString(); // Converts the value of getText to a string.
            if (textString != null && textString.trim().length() ==0)
            {   

                Context context = getApplicationContext();
                CharSequence error = "Please enter a track name" + textString;
                int duration = Toast.LENGTH_LONG;

                Toast toast = Toast.makeText(context, error, duration);
                toast.show();


            }
            else 
            {

                SQLiteDatabase db = waypoints.getWritableDatabase();
                ContentValues trackvalues = new ContentValues();
                trackvalues.put(TRACK_NAME, textString);
                trackvalues.put(TRACK_START_TIME,tracktimeidentifier );
                insertid=db.insertOrThrow(TRACK_TABLE_NAME, null, trackvalues);

            }

But this just closes the Alert Dialog and then displays the Toast. I want the Alert Dialog to still be on the screen.

Thanks

© Stack Overflow or respective owner

Related posts about android

Related posts about java