I am trying to implement an MVP architecture by following Google's sample todo app
The problem I have is that I am getting a NPE when starting my presenter in the onResume()
of the fragments. This happens when I change the orientation of the device.
I have a FragmentPagerAdapter
with two static fragments.
From what I understand the FragmentPagerAdapter
is meant to retain the fragments when the screen is rotated which implies the fragments would retain their presenters. However the presenters are null in onResume()
so there is something I am not understanding.
Here is my current FragmentPagerAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FragmentA fragA = FragmentA.newInstance();
PresenterA presA = new PresenterA(fragA);
return fragA;
case 1:
FragmentB fragB = FragmentB.newInstance();
PresenterB presB = new PresenterB(fragB);
return fragB;
}
return null;
}
@Override
public int getCount() {
return 2;
}
}
So it turns out even with a FragmentPagerAdapter
the fragment is actually destroyed after configuration changes (eg. screen is rotated), so my initial assumption was wrong. I found this out by overring and adding a print statement in the fragment's onDestroy
method.
In my case in order to retain the presenter I just had to setRetainInstance(true)
in the fragment's onCreate
method.