I have a problem with an AlertDialog in Android.
In a class “Misc” there is a method which creates an alertdialog.
public static void getAlert (Context context)
{
Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Notruf absenden?");
builder.setMessage("automatischer Notruf in 60 sec.");
builder.setCancelable(true);
builder.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
callEmergency(context);
}
});
builder.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
countdown.cancel();
}
});
final AlertDialog alertBox = builder.create();
alertBox.show();
countdown = new CountDownTimer(60000, 1000)
{
public void onTick(long millisUntilFinished)
{
alertBox.setMessage("automatischer Notruf in "+ (millisUntilFinished/1000) + " sec.");
}
public void onFinish()
{
alertBox.cancel();
callEmergency(context);
}
}.start();
When I call the method in the main activity by typing:
Misc.getAlert(this)
it works, but in another class named Algorithm I call it in the same way:
Misc.getAlert(context)
But then there is this exception:
09-16 17:15:32.304: E/AndroidRuntime(19797): FATAL EXCEPTION: main
09-16 17:15:32.304: E/AndroidRuntime(19797): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
09-16 17:15:32.304: E/AndroidRuntime(19797): at android.view.ViewRoot.setView(ViewRoot.java:536)
09-16 17:15:32.304: E/AndroidRuntime(19797): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
09-16 17:15:32.304: E/AndroidRuntime(19797): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
09-16 17:15:32.304: E/AndroidRuntime(19797): at android.app.Dialog.show(Dialog.java:241)
09-16 17:15:32.304: E/AndroidRuntime(19797): at de.smehner.Sturzerkennung.Misc.getAlert(Misc.java:220)
09-16 17:15:32.304: E/AndroidRuntime(19797): at de.smehner.Sturzerkennung.Algorithm.fall(Algorithm.java:203)
09-16 17:15:32.304: E/AndroidRuntime(19797): at de.smehner.Sturzerkennung.Algorithm.performNonGraphical(Algorithm.java:68)
09-16 17:15:32.304: E/AndroidRuntime(19797): at de.smehner.Sturzerkennung.SensorValueReceiver.onSensorChanged(SensorValueReceiver.java:66)
09-16 17:15:32.304: E/AndroidRuntime(19797): at android.hardware.SensorManager$ListenerDelegate$1.handleMessage(SensorManager.java:538)
I tried to set in getAlert
Builder builder = new AlertDialog.Builder(Sturzerkennung.this); // Sturzerkenung is the main activity
But then there is the error: “No enclosing instance of the type Sturzerkennung is accessible in scope”
context.getApplicationContext instead of Sturzerkennung.this didn’t solve the problem either.
Has anybody an idea for this problem?
Problem solved..
The context in the Algorithm class was not from the Activity Sturzerkennung…
In Sturzerkennung I put
and then in Algorithm the parameter for getAlert is
Now it works..