karthik kolanji
karthik kolanji

Reputation: 2104

Activity has leaked window android

I facing this issues on dialog.show(). Done google search , tried to modify nothing helped me .

public void openCameraOrGallery(){

     final Dialog dialog = new Dialog(LoginActivity.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.choosecamera);
    dialog.getWindow().setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.WRAP_CONTENT);

    txtGalleryPhoto = (TextView) dialog
            .findViewById(R.id.txt_gallery_photo);
    txtCamera = (TextView) dialog.findViewById(R.id.txt_camera);
    btnClose = (ImageButton) dialog.findViewById(R.id.btn_close);
    btnClose.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    txtGalleryPhoto.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, RESULT_LOAD_IMAGE);
            //dialog.dismiss();
        }
    });
    txtCamera.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
            //dialog.dismiss();

        }
    });

    dialog.show();

}

Upvotes: 0

Views: 112

Answers (1)

Don Chakkappan
Don Chakkappan

Reputation: 7560

Obviously Leaked Window Exception will come in your code.

You are not supposed to change the Activity while showing the dialogue (Because your context will be get changed).

So , you have to continuously check the current context and if there is any change in your current context you should dismiss the dialogue .

In your case dismiss the dialogue just before you start a new Activity

Update

Normal dialogue will be automatically get cancelled.Here is a tricky way to achieve the Login check.

alert.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            Button button = alert.getButton(AlertDialog.BUTTON_POSITIVE);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                  // Code to check the login credentials.
                  if(everythingIsOK)
                  {
                   dialogue.dismiss();
                 }
                 else
                 {
                   // Acknowledge the user 
                     }

                }
            });
        }
    });

Upvotes: 1

Related Questions