I've got a problem with my android app crashing when trying to restore my fragments. I have not added any custom variables to the bundle that I'm trying to restore, It's all default. I'm using Fragments and ViewPager. See my code snippets below:
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return NUM_ITEMS;
}
public int getCurrentItemPosition(Fragment fragment){
return getItemPosition(fragment);
}
@Override
public Fragment getItem(int position) {
return ContentFragment.newInstance(position);
}
}
public class MyActivity extends FragmentActivity {
static final int NUM_ITEMS = 100000;
public int currentSelectedPage;
private int changeToFragmentIndex;
public DateTime midDate;
MyAdapter mAdapter;
ViewPager mPager;
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diary);
MyApplication application = (MyApplication)getApplication();
application.dataController.myActivity = this;
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
int newDay = application.daysBetween(DateTime.now(), DateTime.parse(application.day.dateToShortString()));
this.currentSelectedPage = NUM_ITEMS/2+newDay;
mPager.setCurrentItem(NUM_ITEMS/2+newDay);
mPager.setOnPageChangeListener(new SimpleOnPageChangeListener(){
public void onPageSelected(int position){
currentSelectedPage = position;
ContentFragment fragment = (ContentFragment) mAdapter.instantiateItem(mPager, currentSelectedPage);
fragment.loadData();
}
});
}
}
public class ContentFragment extends Fragment {
private View v;
static final int NUM_ITEMS = 100000;
static ContentFragment newInstance(int num) {
ContentFragment f = new ContentFragment();
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null)
return null;
v = inflater.inflate(R.layout.diarycontent, container, false);
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
setUserVisibleHint(true);
}
}
I receive this stackstrace:
Caused by: java.lang.NullPointerException
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:519)
at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:1 55)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:522)
As I have understood this may be a known problem with the support package and that one possible solution would be to use setUserVisibleHint(true) in onSaveInstanceState. But that didn't help.
Does anyone know another solution to the problem or what I've done wrong?