Search code examples
androidandroid-activityandroid-fragmentactivity

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


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 ?


Solution

  • 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()