Scenario: Activity A opens Activity B, Activity B has two fragments a and b in a viewpager using FragmentPagerAdapter, fragments a and b has some radio buttons and check boxes where the user interacts with;
I need to store the buttons and checkboxes statuses in the fragments even if I left Activity B to A
My Attempts: 1- removed super.onBack() pressed to force the system into calling onSavedInstanceState in the activity, but still couldn't save fragments to it as am instantiating them in the adapter and do not know how to get the same object created of them to activity
2- tried the onSaveInstanceState(), onViewStateRestored() in each fragment and onSavedInstance never got called using setRetainInstance(true) in the oncreate(); then forced calling onSaveInstanceState() by calling it onPause()
I Read most of available solutions on stack and non of them worked, My Code is as follows;
public class FilterPagerAdapter extends FragmentPagerAdapter {
public final static int KEYWORDS_TAB = 0;
public final static int AREAS_TAB = 1;
private int tabCount;
private Context context;
public FilterPagerAdapter(FragmentManager fm, int tabCount, Context context) {
super(fm);
this.tabCount = tabCount;
this.context = context;
}
@Override
public Fragment getItem(int position) {
Fragment fragment;
switch (position) {
case KEYWORDS_TAB:
fragment = KeyWordsFragment.newInstance();
break;
case AREAS_TAB:
fragment = AreasFragment.newInstance();
break;
default:
return null;
}
return fragment;
}
@Override
public int getCount() {
return tabCount;
}
@Override
public CharSequence getPageTitle(int position) {
String tabTitle = "";
switch (position) {
case KEYWORDS_TAB:
tabTitle = context.getResources().getString(R.string.tab_keywords);
break;
case AREAS_TAB:
tabTitle = context.getResources().getString(R.string.tab_area);
break;
default:
}
return tabTitle;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filters);
ButterKnife.bind(this);
mAreas = new Areas();
mKeywords = new KeyWords();
viewControllers();
}
private void viewControllers() {
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_keywords), CATEGORIES_TAB);
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_area), BRANDS_TAB);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.addOnTabSelectedListener(this);
filterPagerAdapter = new FilterPagerAdapter(getSupportFragmentManager(),
tabLayout.getTabCount(), this);
viewPager.setAdapter(filterPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
@Override
public void onBackPressed() {
startActivity(new Intent(FiltersActivity.this, BranchesActivity.class));
}
@Override
public void onStop() {
super.onStop();
tabLayout.removeOnTabSelectedListener(this);
}
}