Snippet - how getActivity () returns null AFTER onAttach

I have a manager class, which is a saved fragment, and it contains the non-preserved fragments and AsyncTasks of these fragments.

After turning the screen, I want to associate new fragments and ongoing / completed tasks with each other and update the fragments with the data provided by the task.

Now in my saved snippet I have the following code:

@Override public void onAttach(Activity activity) { mFragStatePagerAdapter.update(activity.getSupportFragmentManager()); Debugger.Debug(DEBUG, getClass(), "ON_ATTACH_0: parentActivity: {" + (activity != null ? activity.hashCode() : "NULL") + "}"); for (int i = 0; i < mFragStatePagerAdapter.getFragmentListSize(); i++) { Frag f = mFragStatePagerAdapter.tryGetItem(i); if (f != null) f.onAttach(activity); // alternatively I tried following as well // if (f != null) // activity.getSupportFragmentManager().beginTransaction().attach(f).commit(); Debugger.Debug(DEBUG, getClass(), "ON_ATTACH_1: this: " + this.hashCode() + " fragment: " + f + ", parentActivity: {"+ (f.getActivity() != null ? f.getActivity().hashCode() : "NULL") + "}"); } for (int i = 0; i < mTasks.size(); i++) { if (mTasks.get(i) != null) { Frag f = getFragment(i); mTasks.get(i).attach(f, mTaskCallbacks.get(i)); if (mTasks.get(i).getStatus() == Status.FINISHED) mTasks.get(i).deliverResult(); } } super.onAttach(activity); } 

For an explanation:

  • Frag ... is a class extending a fragment
  • mFragStatePagerAdapter ... is an advanced FragmentStatePagerAdapter with functionality for retrieving fragments by index ...

Now my problem is the following (shortened) debug output:

ON_ATTACH_0: parentActivity: {1123400376}

ON_ATTACH_1: this: 1121944544 snippet: ExerciseViewFragment {42e2da98}, parentActivity: {NULL}

So why, after calling f.onAttach(activity) , f.getActivity() returns null? I DO NOT override onAttach in my extended fragment class, so this cannot be the reason ...

+4
source share
2 answers

According to the documentation from https://developer.android.com/reference/android/support/v4/app/Fragment.html#getActivity ()

getActivity() can return null if the fragment is context bound.

And according to this documentation https://developer.android.com/reference/android/support/v4/app/Fragment.html#onAttach(android.app.Activity) , onAttach(Activity activity) deprecated, so use onAttach(Context) instead.

0
source

I think your problem is calling

super.onAttach(activity);

at the end of your onAttach method. Call it first in this method, for example:

 @Override public void onAttach(Activity activity) { super.onAttach(activity) // and here goes your code [...] } 
0
source

Source: https://habr.com/ru/post/1492129/


All Articles