Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
    }
}
like image 301
Waza_Be Avatar asked Jun 08 '13 19:06

Waza_Be


People also ask

Can getActivity be null?

getActivity() returns null in Fragment function. Bookmark this question. Show activity on this post. and yes when I call it (from the Activity), it is null...

What is onAttach in fragment?

onAttach(Activity) called once the fragment is associated with its activity. onCreate(Bundle) called to do initial creation of the fragment. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.


1 Answers

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

like image 153
Neoh Avatar answered Sep 28 '22 03:09

Neoh