Christer
Christer

Reputation: 3076

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 ?

Upvotes: 1

Views: 3850

Answers (2)

Sandy
Sandy

Reputation: 1005

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

Upvotes: 5

Iga Stępniak
Iga Stępniak

Reputation: 136

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

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

Upvotes: 1

Related Questions