I have a Fragment Pager on my app main activity. I also have an action bar button that sets some values and then requests one of the fragments (the dashboard fragment) to be refreshed (the action bar button is only visible when the dashboard fragment is the one being shown) It works fine except, when the system reclaims memory (task away and open several other apps and go back to my app)
When I click the action bar button, and reach refreshDashboard() I get a NPE as the dashboard fragment is null.
Indeed getItem() only gets called when the host activity is created initially but not when the activity is created a 2nd time.
i tried creating the fragments in an override of instanciateItem() but that just created blank fragments.
Making the adapter implement Parcelable might be tedious.
Is there a save way to recreate the fragments (without leaking anything) when the system has reclaimed memory?
My Activity:
public class HomeActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
enableActionBarOverflow();
mPager = (ViewPager) findViewById(R.id.home_view_pager);
mTabStrip = (PagerTabStrip) findViewById(R.id.home_pager_header);
mPagerAdapter = HomePagerAdapter.newInstance(getSupportFragmentManager(), this);
mPager.setAdapter(mPagerAdapter);
}
}
and my adapter:
public class HomePagerAdapter extends FragmentPagerAdapter {
public HomePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
private DashboardFragment dashboardFragment;
private ListFragment listFragment;
private static Context mContext;
@Override
public int getCount() {
return 2;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
dashboardFragment = DashboardFragment.newInstance();
return dashboardFragment;
case 1:
listFragment = ListFragment.newInstance();
return listFragment;
}
return null;
}
public void refreshDashboard(){
dashboardFragment.refresh();
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return mContext.getResources().getString(R.string.tab_dashboard);
case 1:
return mContext.getResources().getString(R.string.tab_list);
}
return "";
}
public static HomePagerAdapter newInstance(FragmentManager supportFragmentManager, Context context) {
HomePagerAdapter homePagerAdapter = new HomePagerAdapter(supportFragmentManager);
mContext = context.getApplicationContext();
return homePagerAdapter;
}
}