Replacing a fragment from ViewPager android - android

SCENARIO
I am creating a fragment structure with dynamic fragment creations. Each item in the fragment creates the next fragment. In the scenario I am storing all these fragments in the ArrayList of fragments so that I can easily replace the created fragment.
PROBLEM
Now I am replacing a fragment from the ArrayList by removing the fragment from a particular index and adding the new one. But when I try to get the fragment from that particular index it returns me the old data without calling the getItem function of the FragmentStateAdapter again.
Here is my Main class.
MainActivity.java
public class MainActivity extends FragmentActivity implements
onPageSelectedListener {
SectionsPagerAdapter mSectionsPagerAdapter;
static int current, listItem;
static String TAG = "MainActivity";
static ViewPager mViewPager;
static ArrayList<Fragment> FragmentList;
static ArrayList<String> titles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
public void init(){
FragmentList = new ArrayList<Fragment>();
titles = new ArrayList<String>();
mViewPager = (ViewPager) findViewById(R.id.pager);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public void addPage(int position, String title, String file, String tag) {
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putString(DummySectionFragment.ARG_FILE_NAME, file);
args.putString(DummySectionFragment.ARG_FILE_TAG, tag);
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position);
fragment.setArguments(args);
titles.add(position, title);
FragmentList.add(position, fragment);
}
public void NextScreen(int position, String title, String file, String tagname) {
if(FragmentList.size()>(position-1)){
for(int i=position; i<FragmentList.size(); i++){
FragmentList.remove(i);
}
}
addPage(position, title, file, tagname);
mViewPager.setCurrentItem(position);
}
public static class PageChanger extends
ViewPager.SimpleOnPageChangeListener {
private int currentPage;
#Override
public void onPageSelected(int position) {
currentPage = position;
}
public int getCurrentScreen() {
return currentPage;
}
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
addPage(0, "Main Fragment", "test.xml", "mytag");
}
#Override
public Fragment getItem(int position) {
return FragmentList.get(position);
}
#Override
public int getCount() {
return FragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "Main Categories";
}
getItem(position);
return titles.get(position);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
}
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public static final String ARG_FILE_NAME = "file_name";
public static final String ARG_FILE_TAG = "tag_name";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
savedInstanceState = this.getArguments();
ListView parent_list = new ListView(getActivity());
String file_name = savedInstanceState.getString(ARG_FILE_NAME);
String tag_name = savedInstanceState.getString(ARG_FILE_TAG);
int current_level = savedInstanceState.getInt(ARG_SECTION_NUMBER);
PullParser pull = new PullParser(getActivity());
pull.pullXml(file_name, tag_name);
parent_list.setAdapter(new ListAdapter(getActivity(),
PullParser.Xml_Tag_Info, current_level));
return parent_list;
}
}
#Override
public void onPageSelected(int pageno) {
current = pageno;
}
}

I have found the answer just to reinstantiate the adapter after making the necessary changes. The edited code is here.
MainActivity.java
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
static int current, listItem;
static String TAG = "MainActivity";
static boolean flag = false;
/**
* The {#link ViewPager} that will host the section contents.
*/
static ViewPager mViewPager;
static ArrayList<DummySectionFragment> FragmentList;
static ArrayList<String> titles;
static FragmentManager fragManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
public void init() {
FragmentList = new ArrayList<DummySectionFragment>();
titles = new ArrayList<String>();
mViewPager = (ViewPager) findViewById(R.id.pager);
fragManager = getSupportFragmentManager();
mSectionsPagerAdapter = new SectionsPagerAdapter(fragManager);
mViewPager.setAdapter(mSectionsPagerAdapter);
titles.add(0, "Main Categories");
}
public void addPage(final int position, String file, String tag) {
DummySectionFragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putString(DummySectionFragment.ARG_FILE_NAME, file);
args.putString(DummySectionFragment.ARG_FILE_TAG, tag);
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position);
fragment.setArguments(args);
try {
FragmentList.set(position, fragment);
} catch (IndexOutOfBoundsException e) {
FragmentList.add(position, fragment);
} catch (Exception e) {
e.printStackTrace();
}
}
public void destroyFragment(int position) {
SectionsPagerAdapter pagerAdapter = (SectionsPagerAdapter) mViewPager
.getAdapter();
pagerAdapter.destroyItem(mViewPager, position,
FragmentList.get(position));
pagerAdapter.notifyDataSetChanged();
}
public void addFragment(int position, Object object) {
SectionsPagerAdapter pagerAdapter = (SectionsPagerAdapter) mViewPager
.getAdapter();
pagerAdapter.notifyDataSetChanged();
}
public void NextScreen(int position, String title, String file,
String tagname) {
if (FragmentList.size() > position - 1) {
for (int i = FragmentList.size() - 1; i > position; i--) {
titles.remove(i);
FragmentList.remove(i);
}
titles.trimToSize();
FragmentList.trimToSize();
}
titles.add(position, title);
addPage(position, file, tagname);
mViewPager.setAdapter(new SectionsPagerAdapter(fragManager));
mViewPager.setCurrentItem(position);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
addPage(0, "catlist.xml", "pid-0");
}
#Override
public Fragment getItem(int position) {
return FragmentList.get(position);
}
public void setId() {
}
#Override
public int getCount() {
return FragmentList.size();
}
#Override
public int getItemPosition(Object object) {
return FragmentList.indexOf(object);
}
#Override
public CharSequence getPageTitle(int position) {
Log.v("titlePosition", position + "");
return titles.get(position);
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static ArrayList<Xml_Item_Data> resultList = new ArrayList<Xml_Item_Data>();
public static final String ARG_SECTION_NUMBER = "section_number";
public static final String ARG_FILE_NAME = "file_name";
public static final String ARG_FILE_TAG = "tag_name";
ListView parent_list;
public static Bundle setValues;
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
savedInstanceState = this.getArguments();
parent_list = new ListView(getActivity());
String file_name = savedInstanceState.getString(ARG_FILE_NAME);
String tag_name = savedInstanceState.getString(ARG_FILE_TAG);
int current_level = savedInstanceState.getInt(ARG_SECTION_NUMBER);
PullParser pull = new PullParser(getActivity());
pull.pullXml(file_name, tag_name);
ListAdapter list_Creator = new ListAdapter(getActivity(),
PullParser.Xml_Tag_Info, current_level);
parent_list.setAdapter(list_Creator);
return parent_list;
}
}
}

I think you can try return POSITION_NONE in your getItemPosition() method. Like here: How to force ViewPager to re-instantiate its items

Related

False data in customList in a dynamically created fragment

I have an Activity with 2 fragments.
Declared a ParentTabFragment in my Activity in which there is a TabLayout and a ViewPager.
There's a method in my ParentTabFragment called addPage which gets called in the Activity.
The addPage has another method called addFrag which is called from a ViewPagerAdapter creating the views in the ChildTabFragment dynamically.
There is a for loop which runs in the Activity, so the Fragments are created according to the number of items in the customList, creating the amount of tabs and pages in the Fragments.
In my ChildTabFragment I load a customList on tab selection event,
when I select a Tab in the ParentTabFragment, I call a getTabID() method from the ChildTabFragment and send the id of the Tab due to which I load the customList according to the id in the ParentTabFragment.
Problem is when I swipe or select tabs, duplicate/false data gets created in the customList.
I get the proper Id of the selected tab but when I try to pass it in the method, random id is called.
In my Activity Class:
for (int j =0;j<it.size();j++){
parentTabFragment.addPage(it.get(j).getTabMenuItem(), it.get(j).getTabMenuId() , selectedMenu);
}
ParentTabFragment:
public void addPage(String pagename, String pageId, String selectedMenu) {
Bundle bundle = new Bundle();
bundle.putString("data", pagename);
//bundle.putString("pageID", pageId);
childTabFragment = new ChildTabFragment();
childTabFragment.setArguments(bundle);
adapter.addFrag(childTabFragment, pagename, pageId);
adapter.notifyDataSetChanged();
if (selectedMenu == null) {
viewPager.setCurrentItem(0);
} else {
for (int i = 0; i < tabLayout.getTabCount(); i++) {
if (tabLayout.getTabAt(i).getText().equals(selectedMenu)) {
viewPager.setCurrentItem(i);
}
}
}
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
ChildTabFragment:
public class ChildTabFragment extends Fragment {
String childname;
int menuItemId;
TextView textViewChildName, txtViewItemId;
ListView childTabMenuList;
private ArrayList<ChildTabMenu_POJO> childTabMenuPojoList = new ArrayList<>();
private ListView listView;
private ChildTabMenuAdapter childTabMenuAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.child_tab_fragment, container, false);
Bundle bundle = getArguments();
childname = bundle.getString("data");
getIDs(view);
return view;
}
private void getIDs(View view) {
childTabMenuList = (ListView) view.findViewById(R.id.childTabMenuList);
loadChildMenu();
}
private void loadChildMenu(menuItemId) {
ChildTabMenu_POJO menu_pojo4 = new ChildTabMenu_POJO(String.valueOf(menuItemId), "4");
childTabMenuPojoList.add(menu_pojo4);
childTabMenuAdapter = new ChildTabMenuAdapter(childTabMenuPojoList, getActivity());
childTabMenuList.setAdapter(childTabMenuAdapter);
}
public void getTabID(int tabId) {
menuItemId = tabId;
Log.e("updatefrag", String.valueOf(menuItemId));
}
}
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<Adapter_POJO> mFragmentTitleList = new ArrayList<>();
Context context;
ViewPager viewPager;
TabLayout tabLayout;
Adapter_POJO adapter_pojo;
public ViewPagerAdapter(FragmentManager manager, Context context, ViewPager viewPager,
TabLayout tabLayout) {
super(manager);
this.context = context;
this.viewPager = viewPager;
this.tabLayout = tabLayout;
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public int getItemCount() {
return mFragmentTitleList.size();
}
public void addFrag(Fragment fragment, String title, String pageId) {
mFragmentList.add(fragment);
adapter_pojo = new Adapter_POJO(title,pageId);
mFragmentTitleList.add(adapter_pojo);
}
public View getTabView(final int position) {
View view = LayoutInflater.from(context).inflate(R.layout.view_pager_adapter_layout, null);
TextView tabItemName = (TextView) view.findViewById(R.id.textViewTabItemName);
tabItemName.setText(mFragmentTitleList.get(position).adapterMenuItem);
tabItemName.setTextColor(context.getResources().getColor(android.R.color.background_light));
return view;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position).adapterMenuItem;
}
public String getPageId(int position){
return mFragmentTitleList.get(position).adapterMenuId;
}
}
If i understand your question so you need to create newInstance constructor for creating fragment with arguments
public static ChildTabFragment newInstance(int page, String title) {
FirstFragment fragmentFirst = new FirstFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
And Store instance variables based on arguments passed in your ChildTabFragment .
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
And now update the view in your onCreateView method
TextView tvLabel = (TextView) view.findViewById(R.id.tvLabel);
tvLabel.setText(page + " -- " + title);
And the main thing you should returns the ChildTabFragment to display for that page from your ViewPagerAdapter like this.
#Override
public Fragment getItem(int position) {
return ChildTabFragment.newInstance(position,"page "+String.valueOf(position));
}

How to destroy a Fragment programmatically in FragmentStatePagerAdapter

I'm using the MainActivity's SearchView here to filter the listview which is showing under tabs but there is an issue of the state of Fragment.
It filters perfectly but when I select first Tab(ADVISORY), then it filters the child of this Tab. And after selecting next Tab(TOP ADVISORY), it filters all listview of the child of this tab but it stops filtering in previous Tab (ADVISORY). And at last I move to the EXPERTVIEW it works only for it not for others.
After lots of debugging I found that it doesn't get destroy when we select another Parent Tab so now I wanna know how I can remove a fragment from its adapter on unselected and reselect on selected again.
MainTabFragment.java
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1, index = 0;
int position_tab = 0;
Bundle args;
int Current_tab = 0;
public static MyTabLayout myTabLayout;
private static MainTabFragment sMainTabFragment;
public static NonSiwpablePager pager;
private Fragment mFragment;
SharedPreferences pref;
private static final int NUM_ITEMS = 2;
List<Integer> TABLE;
public MainTabFragment() {
// Required empty public constructor
}
public static MainTabFragment getInstance() {
return sMainTabFragment;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
pager = (NonSiwpablePager) view.findViewById(R.id.pager);
final ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
pager.setOffscreenPageLimit(NUM_ITEMS-1);
changeTab();
final Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null) {
pager.setCurrentItem(position_tab);
}
index = pager.getCurrentItem();
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
// ViewPagerAdapter adapter = ((ViewPagerAdapter)pager.getAdapter());
final Fragment fragment22 = mAdapter.getRegisteredFragment(pager.getCurrentItem());
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
myTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
// mAdapter.destroyAllItem();
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
return view;
}
public void changeTab() {
Current_tab = pager.getCurrentItem();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
public void setCurrentItem(int item) {
pager.setCurrentItem(item);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
AdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
TopAdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
ExperViewPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
private Fragment mCurrentFragment;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
#Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
#Override
public Fragment getItem(int position) {
Log.e("Fragmentss", (Fragment) maps.get(position).get(KEY_FRAGMENT) + "");
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (mCurrentFragment != object) {
mCurrentFragment = (Fragment) object;
}
super.setPrimaryItem(container, position, object);
}
#Override
public int getCount() {
return maps.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
}

Android Parcel in ViewPager

I'm using ViewPager in my app and when I press home button during the interaction with ViewPager, the app crashes and I get this error:
3780-3780/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Parcel: unable to marshal value OrdinaryFragment{42000b70 #0 id=0x7f090005 android:switcher:2131296261:0}
at android.os.Parcel.writeValue(Parcel.java:1235)
at android.os.Parcel.writeList(Parcel.java:622)
at android.os.Parcel.writeValue(Parcel.java:1195)
at android.os.Parcel.writeMapInternal(Parcel.java:591)
at android.os.Bundle.writeToParcel(Bundle.java:1619)
at android.os.Parcel.writeBundle(Parcel.java:605)
at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:2245)
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:2912)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4895)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
at dalvik.system.NativeStart.main(Native Method)
I know that there's some Serialization problem but I have no idea why I have this problem.
Here's my code:
ViewPager:
public class ViewPagerActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link android.support.v4.view.ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
/**
* DBManager Class for comunicating with DataBase
*/
private DBManager dbManager;
/**
* Fragment ArrayList for ViewPager's adapter input
*/
private ArrayList<Fragment> adapterList;
private ArrayList<String> sectionTitleList;
private long recId;
private MasterDataWithRecIdI masterData;
private static final int NEW_RECORD = -1;
private static final String LAYOUT_ID = "LayoutId";
private static final int NUMBER_OF_PAGES = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbManager = new DBManager();
masterData = (MasterDataWithRecIdI) getIntent().getSerializableExtra("MasterData");
if(savedInstanceState != null) {
ArrayList<Fragment> savedList = (ArrayList<Fragment>) savedInstanceState.getSerializable("Adapter");
initFragments(masterData, savedList);
}else{
initFragments(masterData, null);
}
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(mSectionsPagerAdapter.getCount());
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("Adapter", adapterList);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.viewpager_menu, menu);
return true;
}
/**
* Initializing Fragments and SectionsPagerAdapter
*/
private void initFragments(MasterDataWithRecIdI masterData, ArrayList<Fragment> savedAdapter) {
instantiateTitleArray();
if(savedAdapter == null){
adapterList = new ArrayList<Fragment>();
Fragment fm;
Bundle bundle;
int layoutId = 0;
for (int i = 0; i < 3; i++) {
switch(i) {
case 0:
layoutId = R.layout.client_information_page;
break;
case 1:
layoutId = R.layout.loan_information_page;
break;
case 2:
layoutId = R.layout.additional_information_1_page;
break;
}
bundle = new Bundle();
bundle.putInt(LAYOUT_ID, layoutId);
fm = new OrdinaryFragment();
fm.setArguments(bundle);
adapterList.add(fm);
}
fm = new LastFragment();
adapterList.add(fm);
recId = NEW_RECORD;
if (masterData != null) {
recId = masterData.getRecId();
}
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), adapterList, sectionTitleList, recId, dbManager);
((LastFragment) fm).setSectionsPagerAdapter(mSectionsPagerAdapter, dbManager);
} else {
recId = NEW_RECORD;
if (masterData != null) {
recId = masterData.getRecId();
}
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), savedAdapter, sectionTitleList, recId, dbManager);
}
}
OrdinaryFragment:
public class OrdinaryFragment extends Fragment {
private static final String LAYOUT_ID = "LayoutId";
private int layoutId;
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.setRetainInstance(true);
layoutId = getArguments().getInt(LAYOUT_ID);
View rootView = inflater.inflate(layoutId, container, false);
ArrayList<DetailsItemI> list = (ArrayList<DetailsItemI>)getArguments().getSerializable("ViewData");
ViewFillerController viewFiller = new ViewFillerController();
viewFiller.fillTheView(rootView, list);
return rootView;
}
}
SectionsPagerAdapter:
public class SectionsPagerAdapter extends FragmentPagerAdapter implements Serializable{
private static final int NEW_RECORD = -1;
private ArrayList<Fragment> fragmentList;
private ArrayList<String> sectionTitleList;
private long recId;
private DBManager dbManager;
public SectionsPagerAdapter(FragmentManager fm, ArrayList<Fragment> fragmentList, ArrayList<String> sectionTitleList, long recId, DBManager dbManager) {
super(fm);
this.fragmentList = fragmentList;
this.sectionTitleList = sectionTitleList;
this.recId = recId;
this.dbManager = dbManager;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a OrdinaryFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = this.fragmentList.get(position);
Bundle args;
if (fragment.getArguments() == null) {
args = new Bundle();
}else{
args = fragment.getArguments();
}
args.putInt(OrdinaryFragment.ARG_SECTION_NUMBER, position + 1);
args.putLong("RecordID", recId);
if(recId != NEW_RECORD){
args.putSerializable("ViewData", getTabViewValues(recId, position));
}
if(fragment.getArguments() == null) {
fragment.setArguments(args);
}
return fragment;
}
private ArrayList<DetailsItemI> getTabViewValues(long recId, int tabId){
return dbManager.selectDetailsWithRecIdAndTabId(recId, tabId);
}
#Override
public int getCount() {
return this.fragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
if(sectionTitleList == null){
return "";
}
return this.sectionTitleList.get(position).toUpperCase(l);
}
}
Custom TextView where I use Parcelable:
public class XTextView extends TextView {
private String viewParameter;
public XTextView(Context context, AttributeSet attrs) {
super(context, attrs);
getViewAttributes(context, attrs);
}
public String getXViewParameter(){
return String.valueOf(this.viewParameter);
}
public String getXValue(){
return String.valueOf(this.getText());
}
public void setXValue(String xValue) {
this.setText(xValue);
}
/**
* Getting all attributes of view Id-s.
*
* #param context
* #param attrs
*/
private void getViewAttributes(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.XTextView);
final int N = a.getIndexCount();
for(int i = 0; i < N; i++){
int attr = a.getIndex(i);
switch(attr){
case R.styleable.XTextView_viewParameter:
viewParameter = a.getString(attr);
break;
}
}
a.recycle();
}
#Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedStateTextView ss = new SavedStateTextView(superState);
ss.stateToSave = String.valueOf(this.getText().toString());
return ss;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
if(!(state instanceof SavedStateTextView)) {
super.onRestoreInstanceState(state);
return;
}
SavedStateTextView ss = (SavedStateTextView) state;
super.onRestoreInstanceState(ss.getSuperState());
this.setText(ss.stateToSave);
}
}
SavedStateTextView class:
public class SavedStateTextView extends View.BaseSavedState {
String stateToSave;
public SavedStateTextView(Parcelable superState) {
super(superState);
}
private SavedStateTextView(Parcel in) {
super(in);
this.stateToSave = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(this.stateToSave);
}
public static final Parcelable.Creator<SavedStateTextView> CREATOR =
new Parcelable.Creator<SavedStateTextView>() {
#Override
public SavedStateTextView createFromParcel(Parcel source) {
return new SavedStateTextView(source);
}
#Override
public SavedStateTextView[] newArray(int size) {
return new SavedStateTextView[size];
}
};
}
I hope there'll be some help.
Thanks in advance.
SOLVED
see answer below.
I Solved My problem.
The Fragments That I was using in my ViewPager weren't Serializable. I just made them implement Serializable Interface and now it works fine.

need help to fix code for getting current view in viewpager

Need help to fix a code I saw in a https://stackoverflow.com/a/9275732/1938357. The solution I need is get the current view onany page in my viewpager based application
Below is the code for reference
public View getCurrentView(ViewPager pager) {
for (int i = 0; i < pager.getChildCount(); i++) {
View child = pager.getChildAt(i);
if (child.getX() <= pager.getScrollX() + pager.getWidth()
&& child.getX() + child.getWidth() >= pager.getScrollX() + pager.getWidth()) {
return child;
}
}
return getChildAt(0);
I am trying to access the current view in the view pager and used the code above. It works fine when I scroll forwards. But when I scroll backwards then after 2 backward scrolls this stops working.
Public class myActivity extends FragmentActivity
//Variable declarations
protected void onCreate(Bundle savedInstanceState) {
ViewPager mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
View CurrView;
OnPageChangeListener pageChangelistener = new OnPageChangeListener() {
#Override
public void onPageSelected(int pageSelected) {
doTextViewChnges();//access the text view and update it based on pageSelected
---THIS IS WHERE I AM STUCK IN TRYING TO GET THE TEXTVIEW IN MY CURRENT FRAGMWNT/VIEW-------
}
mPager.setOnPageChangeListener(pageChangelistener);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return ScreenSlidePageFragment.create(position, <other parameters I want to pass>);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
And below is my ScreenSlidePageFragment class
public class ScreenSlidePageFragment extends android.support.v4.app.Fragment {
public static final String ARG_PAGE = "pagenumber";
public static final String ARG_PAGEARRAY = "pages";
private int mPageNumber;
//Declare other variables
#SuppressLint("NewApi")
public static ScreenSlidePageFragment create(int pageNumber, String[] pages, int bookmarkPageNumber, String storyName, int linesInOnePage) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
args.putStringArray(ARG_PAGEARRAY, pages);
fragment.setArguments(args);
return fragment;
}
#SuppressLint("NewApi")
public ScreenSlidePageFragment() {
}
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
pages = getArguments().getStringArray(ARG_PAGEARRAY);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = (ViewGroup) inflater
.inflate(R.layout.activity_story, container, false);
//load layout with all components filled up for that page
loadView(rootView);
return rootView;
}
public int getPageNumber() {
return mPageNumber;
}
It is very hard to discuss in comments with example of code.
As I see in grepcode FragmentStatePagerAdapter.setPrimaryItem(), receive object as android.support.v4.app.Fragment. But you are receive ClassCastException when trying to cast object as Fragment. Can you check your casting: do you really cast object in android.support.v4.app.Fragment not in android.app.Fragment? If all right, add your exception message to your question, please.
UPDATE:
If your ScreenSlidePagerAdapter has method getCurrentView(), then your method 'getCurrentView()' can work like this:
public View getCurrentView(ViewPager pager) {
return ((ScreenSlidePagerAdapter) pager.getAdapter()).getCurrentView();
}
And method getCurrentView() of your ScreenSlidePagerAdapter:
public View getCurrentView() {
return currView;
}
UPDATE 2:
I've made some modification with your code:
Your Activity with private Adapter:
public class myActivity extends FragmentActivity implements ISelectItemListener {
// Your variable declarations and methods
#Override
protected void onCreate(Bundle savedInstanceState) {
final ViewPager pager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
pager.setAdapter(mPagerAdapter);
pager.setOnPageChangeListener(
new OnPageChangeListener() {
#Override
public void onPageSelected(int pageSelected) {
final ScreenSlidePageFragment fragment = mPagerAdapter.getFragment(pageSelected);
if (fragment != null) {
fragment.doTextViewChnges();
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
});
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
//Your variable declarations
private final ScreenSlidePageFragment[] mFragments;
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
mFragments = new ScreenSlidePageFragment[NUM_PAGES];
}
#Override
public int getCount() {
return NUM_PAGES;
}
// It will create new ScreenSlidePageFragment by position if it's not exsist
#Override
public android.support.v4.app.Fragment getItem(int position) {
if (getFragment(position) == null) {
mFragments[position] = ScreenSlidePageFragment.create(position, <other parameters I want to pass>);
}
return getFragment(position);
}
// It will give you ScreenSlidePageFragment if it's exists, or null
public ScreenSlidePageFragment getFragment(int position) {
return mFragments[position];
}
}
}
Your Fragment:
public class ScreenSlidePageFragment extends Fragment {
//Your variables and methods
public static ScreenSlidePageFragment create(int pageNumber, String[] pages, int bookmarkPageNumber, String storyName, int linesInOnePage) {
final Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
args.putStringArray(ARG_PAGEARRAY, pages);
final ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
pages = getArguments().getStringArray(ARG_PAGEARRAY);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = (ViewGroup) inflater.inflate(R.layout.activity_story, container, false);
loadView(rootView);
return rootView;
}
public int getPageNumber() {
return mPageNumber;
}
// Let's keep logic of modifications in fragment
public void doTextViewChnges() {
final View view = getView();
// do what you want with your View and his children
}
}

Dynamically load next fragment with ViewPager

I'm creating a demo app with the new android compatibility library. I want to show two listfragments with ViewPager. The first shows the root categories and the second shows the subcategories. After somebody clicks on root category the viewpager move to the subcategory, but it won't work, because always show the root category elements.
I spend few minutes with debug and I'm realised the ViewPager creates the second fragment after the first one.(I think the pager cache the next view or fragment.)
Is it possible to load the second fragment after onListItemClick?
Here is the code:
public class ViewPagerDemoActivity extends FragmentActivity implements OnBookSelectedListener {
private static int mSelectedCategoryId;
private MyAdapter mMyAdapter;
private ViewPager mPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupPager();
}
private void setupPager() {
mPager = (ViewPager) findViewById(R.id.pager);
mMyAdapter = new MyAdapter(getSupportFragmentManager());
mPager.setAdapter(mMyAdapter);
}
#Override
public void onBookSelected(int categoryId) {
mSelectedCategoryId = categoryId;
if (mSelectedCategoryId == 0) {
mPager.setCurrentItem(1);
} else {
mPager.setCurrentItem(0);
}
}
public static class MyAdapter extends FragmentPagerAdapter {
private static final int NUMBER_OF_FRAGMENTS = 2;
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return BookListFragment.newInstance(mSelectedCategoryId);
}
#Override
public int getCount() {
return NUMBER_OF_FRAGMENTS;
}
}
}
public class BookListFragment extends ListFragment {
private static final String ARGUMENT_KEY = "categoryId";
private OnBookSelectedListener mOnBookSelectedListener;
private int mCategoryId;
public static BookListFragment newInstance(int categoryId) {
BookListFragment bookListFragment = new BookListFragment();
Bundle argument = new Bundle();
argument.putInt(ARGUMENT_KEY, categoryId);
bookListFragment.setArguments(argument);
return bookListFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCategoryId = getArguments() != null ? getArguments().getInt(ARGUMENT_KEY) : 0;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Books.getBooks(mCategoryId)));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.pager_list, container, false);
View tv = v.findViewById(R.id.text);
((TextView) tv).setText("Category :" + mCategoryId);
return v;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (mCategoryId == 0) {
mOnBookSelectedListener.onBookSelected(1);
} else {
mOnBookSelectedListener.onBookSelected(0);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mOnBookSelectedListener = (OnBookSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + "Must Implement OnBookSelectedListener.");
}
}
public interface OnBookSelectedListener {
public void onBookSelected(int categoryId);
}
}
public class Books {
private static final String[] fruits = new String[] { "Apple", "Banana", "Orange" };
private static final String[] category = new String[] { "Lorem", "Dolor", "Ipsum" };
public static String[] getBooks(int categoryId) {
return categoryId == 0 ? category : fruits;
}
}
I solved the problem, I need to add List to the adapter and after that the getItem don't create new instance, only gets the item from the list.
This is the new code.
public class ViewPagerDemoActivity extends FragmentActivity implements OnBookSelectedListener {
private MyAdapter mMyAdapter;
private ViewPager mPager;
private BookOnPageChangeListener mBookOnPageChangeListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupPager();
}
private void setupPager() {
mPager = (ViewPager) findViewById(R.id.pager);
mMyAdapter = new MyAdapter(getSupportFragmentManager());
mPager.setAdapter(mMyAdapter);
mBookOnPageChangeListener = new BookOnPageChangeListener();
mPager.setOnPageChangeListener(mBookOnPageChangeListener);
}
#Override
public void onBookSelected(int categoryId) {
mMyAdapter.addPage(categoryId);
mPager.setCurrentItem(mBookOnPageChangeListener.getCurrentPage() + 1);
}
public static class MyAdapter extends FragmentPagerAdapter {
private List<Fragment> pages;
public MyAdapter(FragmentManager fm) {
super(fm);
initPages();
}
/**
* Create the list and add the first ListFragment to the ViewPager.
*/
private void initPages() {
pages = new ArrayList<Fragment>();
addPage(0);
}
/**
* Add new BookListFragment to the ViewPager.
*
* #param categoryId
* - the category id
*/
public void addPage(int categoryId) {
pages.add(BookListFragment.newInstance(categoryId));
}
#Override
public Fragment getItem(int position) {
return pages.get(position);
}
#Override
public int getCount() {
return pages.size();
}
}
/**
* Get the current view position from the ViewPager.
*/
public static class BookOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
private int currentPage;
#Override
public void onPageSelected(int position) {
// current page from the actual position
currentPage = position;
}
public int getCurrentPage() {
return currentPage;
}
}
}
Have you tried using setOnItemClickListener()?

Categories

Resources