0

I have this method in which i want to create an AlertDialog but when I call it the application stops working when it reaches ad.show

public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is necessary for Traffic Finder");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            //mContext.startActivity(intent);
            startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });

    // Create Alert Dialog
    AlertDialog ad= alertDialog.create();

    // Showing Alert Message
    ad.show();
}

I get this:

08-26 20:47:11.462  28940-29005/? E/AndroidRuntime﹕ FATAL EXCEPTION: IntentService[CoordinatesService]
Process: com.example.manos.trafficfinder, PID: 28940
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:566)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:282)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
        at android.app.Dialog.show(Dialog.java:298)
        at com.example.manos.trafficfinder.GPSTracker.showSettingsAlert(GPSTracker.java:182)
        at com.example.manos.trafficfinder.GeographicCoordinates.getLatitudeString(GeographicCoordinates.java:32)
        at com.example.manos.trafficfinder.DataManagement.addPosition(DataManagement.java:116)
        at com.example.manos.trafficfinder.CoordinatesService.onHandleIntent(CoordinatesService.java:28)
        at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.os.HandlerThread.run(HandlerThread.java:61)
nKn
  • 13,691
  • 9
  • 45
  • 62
Manos
  • 149
  • 1
  • 12

1 Answers1

1

The Context passed to AlertDialog.Builder seems incorrect. Try YourClass.this instead of mContext.

nKn
  • 13,691
  • 9
  • 45
  • 62
  • I changed it to this: AlertDialog.Builder alertDialog = new AlertDialog.Builder(GPSTracker.this); Now the code fails at this line – Manos Aug 26 '15 at 21:14