Why does getActivity of my fragment returns null?

27,158

Your fragment has probably been detached from the activity. See this link for more details.

Share:
27,158
Waza_Be
Author by

Waza_Be

android dev

Updated on June 09, 2020

Comments

  • Waza_Be
    Waza_Be almost 4 years

    I currently have a thread in my main Activity do download stuff frow web and I then need to update the Fragments inside a ViewPager after download finished.

    The download is handled by a service and broadcast an Intent when finished.

    So, basically, my code in my main Activity is:

    public class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ((PositionFragment)mPagerAdapter.getItem(0)).updateUI();
        }
    }
    

    and my PositionFragment:

    public void updateUI() {
        mActivity = getActivity();
    

    I really don't get how this can be null. This really souds simple, but I must be missing something!

    Any idea?

    Edit: my Adapter:

    public class PageAdapter extends FragmentPagerAdapter {
        private List<Fragment> fragments;
    
        public PageAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }
    
        @Override
        public Fragment getItem(int position) {
            return this.fragments.get(position);
        }
    
        @Override
        public int getCount() {
            return this.fragments.size();
        }
    
        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }
    
  • Waza_Be
    Waza_Be almost 11 years
    This code is called after the onResume, so I strongly belive that onAttach was called before ;-)
  • Waza_Be
    Waza_Be almost 11 years
    Sound like a start, but how should I access the Fragment in the Adapter with FragmentManager, like suggested in the answer.. I will try this other solution that looks nice: stackoverflow.com/a/15261142/327402