Search code examples
androidandroid-contextandroid-dialog

Passing the Context always fails - Unable to add window -- token null is not valid; is your activity running?


I am working on an App that has a DialogBuilder Class where I implemented all the Dialogs for the App in order to be able to call them in other Services or Activities; that works very well except in one Activity, where I tried everything to pass the context - it is not working; hence, I would be more than delighted for any hints or help on this, thanks!

The Dialog:

public static void bookingConfirmationDialog(Context mContext) {
        if(mContext != null) {
            final Dialog dialog = new Dialog(GoldbekStorageApp.getInstance(), 0);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setContentView(R.layout.new_booking_layout);
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            TextView textView = dialog.findViewById(R.id.messageId);
            textView.setText(GoldbekStorageApp.getInstance().messageId);
            Button okButton = dialog.findViewById(R.id.ok);
            okButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.show();
        }
    }

The call of the Dialog:

proceedButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                message.setType(type);
                message.setFromId(fromID);
                message.setToId(toID);
                message.setTypeId(typeID);
                message.setTime(time);
                message.setTitle(title);
                message.setReceiptNo(receiptNo);
                message.setNote(note);
                RestClient.putBookingOnPallet(basic,message,context);
                DialogBuilder.bookingConfirmationDialog(context);
       /*         Intent activityChangeIntent = new Intent( NewProductActivity.this,
                        NewProductActivity.class);
                NewProductActivity.this.startActivity(activityChangeIntent);*/

            }
        });

Solution

  • I may be missing something but you could override onAttach in the DialogFragment class instead of passing the context in through the constructor.

        @Override
        public void onAttach(@NonNull Context context) {
            super.onAttach(context);
        }