In my app I got a ViewPager which is showing 3 fragments in a swipe views layout. If the activity is recreated (for example, if I go to landscape mode) I can't get a reference to the fragments anymore.
This is my Adapter
public class TabsPagerAdapter extends FragmentStatePagerAdapter{
public static final String FRAGMENT_MAP = "fragmentMap";
private SparseArray<MyFragment> myFragmentMap = new SparseArray<MyFragment>();
public TabsPagerAdapter(FragmentManager fm){
super(fm);
}
@Override
public Fragment getItem(int arg0) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
String nameOfTab = actionBar.getTabAt(arg0).getText().toString();
ArrayList<VideoBookmark> listOfFragment = myBookmarkManager.getList(nameOfTab);
args.putParcelableArrayList(MyFragment.ARG_LIST, listOfFragment);
fragment.setArguments(args);
myFragmentMap.put(arg0, fragment);
return fragment;
}
@Override
//return mytabs.size()???
public int getCount() {
return NUM_OF_TABS;
}
public void destroyItem (ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
myFragmentMap.remove(position);
}
public Fragment getFragment(int key) {
return myFragmentMap.get(key);
}
public SparseArray<MyFragment> getFragmentMap(){
return myFragmentMap;
}
public void setNewFragmentMap(SparseArray<MyFragment> newMap){
myFragmentMap = newMap;
}
}
I get null pointer exception in this line
//get current fragment
int index = myViewPager.getCurrentItem();
Fragment fragment = myTabsPagerAdapter.getFragment(index);
EditText title = (EditText) fragment.getView().findViewById(R.id.new_title);
I checked, this is happening because the getItem method is not called, so I guess the adapter reuses old fragments in some way, but how can I access this fragments cache to get my old fragments and to be able to use the findViewById method? Thank you!