tags:

views:

99

answers:

2

Hello 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.

regards maxsap.

A: 

Hi there. 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.

Prabhat
A: 

sorry for this but I can't comment all this text stackoverflow doesn't let me. I am doing this on my main activity : public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

    if(somecondition){
        //something
    }else{
        AlertDialog.Builder alert = new AlertDialog.Builder(this.getApplicationContext());

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

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

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

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

        alert.show();
    }
}      

but still having the same problem.

maxsap
it's always better to use YourActivity.this than just this. In example if you are in an inner class.
Rorist
ok found it, seems like you have to override onCreateDialog method and call that using showDialog method.
maxsap