Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

android - getActivity() is null inside handler

I have an app with a single activity and two fragments. Fragment B is added(addedToBackStack) on Top of Fragment A. In Fragment B, I am showing a dialog, going back to Fragment A and then dismissing the dialog. If getActivity()!=null check is removed inside the handler, the code works fine. But getActivity() is null inside handler. Why is getActivity() null inside handler in the following piece of code?

 private void showDialog(final Dialog dialog) {
    dialog.show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (getActivity()!=null && !getActivity().isFinishing()) {
                dialog.dismiss();
            }
        }
    }, 1000);
    if (getActivity() != null && !getActivity().isFinishing())
        getActivity().onBackPressed();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

getActivity() is null because after getActivity().onBackPressed(); call your fragment will get detached from the Activity. So inside handler it will be always null because its getting called with a delay. If you want to dismiss dialog after one second and also move back to previous fragment then you should move onBackPressed inside the run method. i have replaced the null check with isAdded().

private void showDialog(final Dialog dialog) {
    dialog.show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (isAdded()) {
                dialog.dismiss();
                getActivity().onBackPressed();
            }
        }
    }, 1000);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...