ez4nick
ez4nick

Reputation: 10199

getting text from edit text in input dialog

I have an alert dialog like this:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            context);
    EditText input = new EditText(this);
    input.setText(sp.getString("NAME_0",""),TextView.BufferType.EDITABLE);
    alertDialogBuilder.setView(input);
    String name = input.getText().toString();
    alertDialogBuilder.setCancelable(false);
    alertDialogBuilder.setTitle("Enter your name"); //Set the title of the box
    //alertDialogBuilder.setMessage(""); //Set the message for the box
    alertDialogBuilder.setPositiveButton("Start", new DialogInterface.OnClickListener(){
        public void onClick(DialogInterface dialog, int id){
            dialog.cancel(); //when they click dismiss we will dismiss the box
        }
    });
    AlertDialog alertDialog =alertDialogBuilder.create(); //create the box
    alertDialog.show(); //actually show the box

And the problem is that 'name' always seems to be empty. Is there a different way to get the text from an edit text that is inside an alert dialog?

Upvotes: 0

Views: 796

Answers (2)

TronicZomB
TronicZomB

Reputation: 8747

Try the following:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
        context);
EditText input = new EditText(this);
input.setText(sp.getString("NAME_0",""),TextView.BufferType.EDITABLE);
alertDialogBuilder.setView(input);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setTitle("Enter your name"); //Set the title of the box
//alertDialogBuilder.setMessage(""); //Set the message for the box
alertDialogBuilder.setPositiveButton("Start", new DialogInterface.OnClickListener(){
    public void onClick(DialogInterface dialog, int id){
        String name = input.getText().toString();
        dialog.cancel(); //when they click dismiss we will dismiss the box
    }
});
AlertDialog alertDialog =alertDialogBuilder.create(); //create the box
alertDialog.show(); //actually show the box

You were trying to the value of the EdtiText at the time of creation of the dialog, which is empty.

Upvotes: 1

ah008a
ah008a

Reputation: 1145

The method works fine you are just assigning the variable too soon, you need to do it for example when the user clicks the button inside the onClick()

Upvotes: 2

Related Questions