问题
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