Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android prompt user's input using a dialog

Tags:

android

I would like to prompt the user to give me input in my android application using a dialog. this is what I have found:

AlertDialog.Builder alert = new AlertDialog.Builder(this);

alert.setTitle("Title");
alert.setMessage("Message");

// Set an EditText view to get user input 
final EditText input = new EditText(this);
alert.setView(input);

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText();
 // Do something with value!
 }
});

alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int whichButton) {
     // Canceled.
}
});

 alert.show();

but this gives me :

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

is there any problem on my code it seems like a null argument is passed on the dialog but I can't find out what is the problem.

like image 698
maxsap Avatar asked Oct 19 '10 12:10

maxsap


1 Answers

When I ran your code in a new project, it worked fine. So probably "this" that you are using

  • is not an activity
  • is not the activity in view i.e. there might be a parent activity. If it is the child of some activity, use getParent() instead of "this".
  • is null

Hope this helps.

like image 143
Prabhat Avatar answered Nov 03 '22 00:11

Prabhat