Android Fragment - getActivity().runOnUiThread returns null when restarting app

╄→гoц情女王★ 提交于 2019-12-25 03:57:10

问题


when I start the app the first time the code below works just fine. But when leaving the app and opening it again I get an error saying getActivity() returns null.

I'm doing this code in a Fragment:

(getActivity()).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                    enableMenu();
                    openMenu();
                    navigateToFragment(new BlankFragment());
                }
            });

What to do ?

How can I get the Activity ?


回答1:


Create object of Activity and assign that on the onAttach Method like below. Some times getActivity gives null so its a better way to make activity instance in onAttach and use that instance.

private Activity mActivity;

@Override
public void onAttach(Activity activity) {
   super.onAttach(activity);
   mActivity = activity;
}

Now use this object instead of the getActivity()




回答2:


The method onAttach(Activity activity) is now deprecated. You should use this one:

@Override
public void onAttach(Context context) {
super.onAttach(context);
activity = getActivity();
}


来源:https://stackoverflow.com/questions/34039257/android-fragment-getactivity-runonuithread-returns-null-when-restarting-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!