Вопрос

in my activity i use viewpager. I create two fragments and attach the to the view pager and time to time calling some methods from this fragments in my activity.. afer the app is killed on low memory and recreated fragments are there but no connection with the viewpager somehome.. i can not call MyFragment.mymethod().. it says MyFragment is null

 public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            if(position==0){
                if(homeFragment==null){
                    homeFragment=new HomeFragment();
                }
                return homeFragment;
            }else{
                if(mapFragment==null){
                    mapFragment=new Map();
                }
                return mapFragment;
            }
        }

. . .

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id==R.id.action_search){
            return true;
        }else if(id==R.id.action_feedback){

        }else if(id==R.id.action_rate_me){

        }else if(id==R.id.action_show_favorites ){
            if(mViewPager.getCurrentItem()!=0){
                mViewPager.setCurrentItem(0);
            }
            homeFragment.populateListWithFavorites();
            return true;

        }else if(id==R.id.action_history){
            if(mViewPager.getCurrentItem()!=0){
                mViewPager.setCurrentItem(0);
            }
            homeFragment.populateListWithHistory();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
Это было полезно?

Решение

I found the solution....

it is really like a said that my fragment variables in the main activity is cleared so i have no connection to the fragments anymore.. what i did is inside the onAttach() i linked my fragment to the mainActivity variables again

@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = activity;
        ((RestaurantActivityViewPager)mActivity).menuFragment=this;
    }
    public static MenuFragment newInstance(int sectionNumber) {
        MenuFragment fragment = new MenuFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

Другие советы

If you get tabFragment by this code

Fragment fragment = mPagerAdapter.getItem(position);

It caused that bug when low memory. Try with this one

fragment = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.rewards_viewpager + ":"+position);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top