Reputation: 10199
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
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
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