Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android crash in dialog.show()

I am creating a dialog using the getApplicationContext() function and this causes the program to crash when I call dialog.show(). I am using getApplicationContext() because I am trying to make the dialog open within a Camera.PictureCallback() like this:

Camera.PictureCallback pictureCallbackJpeg = new Camera.PictureCallback()
{
    public void onPictureTaken(byte[] data, Camera c)
    {
        Context context = getApplicationContext();
        Dialog dialog = new Dialog(context);
        dialog.setContentView(R.layout.send_dialog);
        dialog.setTitle("Send image?");
        dialog.show();

        camera.startPreview();
    }
};

Here is the crash log:

Thread [<1> main] (Suspended (exception WindowManager$BadTokenException))   
Dialog.show() line: 245 
myApp$1.onPictureTaken(byte[], Camera) line: 31 
Camera$EventHandler.handleMessage(Message) line: 328    
Camera$EventHandler(Handler).dispatchMessage(Message) line: 99  
Looper.loop() line: 143 
ActivityThread.main(String[]) line: 4914    
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]  
Method.invoke(Object, Object...) line: 521  
ZygoteInit$MethodAndArgsCaller.run() line: 868  
ZygoteInit.main(String[]) line: 626 
NativeStart.main(String[]) line: not available [native method]  

Any ideas how to fix this?

like image 878
Tom Leese Avatar asked Apr 28 '11 16:04

Tom Leese


1 Answers

If you are inside an activity (say MyActivity), you can create the Dialog:

Dialog dialog = new Dialog(this);

or if you are inside an inner class of an Activity:

Dialog dialog = new Dialog(MyActivity.this);

Otherwise you could try the getBaseContext().
You just make sure, that you're working in the UI thread.

like image 102
rekaszeru Avatar answered Oct 17 '22 13:10

rekaszeru