5

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];
    }
}
Ahmad
  • 69,608
  • 17
  • 111
  • 137
Waza_Be
  • 39,407
  • 49
  • 186
  • 260
  • As you can see in my Adapter, the getItem returns the created Fragment that exists! – Waza_Be Jun 08 '13 at 19:40
  • It always happens, I have set a code in the onResume of the Fragment to broadcast the Intent it if data is too old. So the Activity+Fragment have just been set in background and then resumed – Waza_Be Jun 08 '13 at 19:46
  • `getActivity()` is returning null because the fragment did not get attached to the Activity yet. Where are you calling `updateUI()`? In `onCreateView()`? – Ahmad Jun 08 '13 at 19:51
  • Possible duplicate of [getActivity() returns null in Fragment function](http://stackoverflow.com/questions/6215239/getactivity-returns-null-in-fragment-function) – rds Nov 12 '15 at 19:17
  • Look for [this link](http://stackoverflow.com/a/27678112/1252158), it might help – Summved Jain Feb 15 '17 at 13:59

2 Answers2

6

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

Community
  • 1
  • 1
Neoh
  • 15,906
  • 14
  • 66
  • 78
  • 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: http://stackoverflow.com/a/15261142/327402 – Waza_Be Jun 08 '13 at 19:59
0

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

asenovm
  • 6,397
  • 2
  • 41
  • 52
  • 4
    This code is called after the onResume, so I strongly belive that onAttach was called before ;-) – Waza_Be Jun 08 '13 at 19:54