Vali79 Vali79 - 3 months ago 30
Java Question

Android Adapter AlertDialog error

I have the following code inside an Adapter class I use for a listview in another class.

AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Introduceti parola:");
final EditText input = new EditText(getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
hash.put("name", Rooms.name);
hash.put("parola", input.getText().toString());
site = siteul + "/join";
new ATask((ViewHolder) v.getTag()).execute(site);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();


The problem is that when I trigger the action I get this error at the
builder.show()
line

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


I thought the
getContext()
was at fault, but it doesn't generate any error in this code in the same Adapter class:

Toast.makeText(getContext(), "Cool message!", Toast.LENGTH_LONG).show();


What could be the problem then?

Answer

Replace getContext() with ActivityName.this.