简体   繁体   中英

Why does getActivity of my fragment returns null?

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];
    }
}

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

You can call getActivity() only after fragment's onAttach method is called. I believe, that's the issue here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM