DialogFragment.dismiss crashing with NullPointerException

后端 未结 6 2023
慢半拍i
慢半拍i 2021-02-18 13:08

I\'m doing some background work and showing a DialogFragment while I do that. Once my work is done and the relevant callback is invoked, I dismiss the dialog. When I do, I get a

6条回答
  •  一整个雨季
    2021-02-18 13:29

    I know this message is old but I ran into a similar case that I needed to solvew without refactoring or changing a lot of code. Hope it's useful for somebody

       package com.example.playback;
    
    import android.os.Bundle;
    import android.support.v4.app.DialogFragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    public class SaferDialogFragment extends DialogFragment {
    
        private boolean allowStateLoss = false;
        private boolean shouldDismiss = false;
    
        public SaferDialogFragment() {
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setRetainInstance(true);
        }
    
        @Override
        public void onStart() {
            super.onStart();
            //check if we should dismiss the dialog after rotation
            if (shouldDismiss) {
                if (allowStateLoss)
                    dismissAllowingStateLoss();
                else
                    dismiss();
            }
        }
    
        @Override
        public void dismiss() {
            if (getActivity() != null) { // it's "safer" to dismiss
                shouldDismiss = false;
                super.dismiss();
            } else {
                shouldDismiss = true;
                allowStateLoss = false;
            }
        }
    
        @Override
        public void dismissAllowingStateLoss() {
            if (getActivity() != null) { // it's "safer" to dismiss
                shouldDismiss = false;
                super.dismissAllowingStateLoss();
            } else
                allowStateLoss = shouldDismiss = true;
        }
    
        //keeping dialog after rotation
        @Override
        public void onDestroyView() {
            if (getDialog() != null && getRetainInstance())
                getDialog().setDismissMessage(null);
            super.onDestroyView();
        }
    
    
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            /** omitted code **/
            return super.onCreateView(inflater, container, savedInstanceState);
        }
    }
    

提交回复
热议问题