Andrew Butler
Andrew Butler

Reputation: 1060

Why is my activity context null in my fragment?

I am trying to create a boilerplate fragment. I keep getting a null reference error though when I try to set the LayoutManager of my RecyclerView:

Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference

Below is the order in which I call to get the error:

Main.class:

public class PagerAdapter extends FragmentPagerAdapter {
    ...
    @Override
    public Fragment getItem(int position){
        switch(position){
            default:
                return new WhatsNew();
        }
    }
}

WhatsNew.class:

public class WhatsNew extends Base {

    private LayoutInflater mInflater;
    private Handler mHandler = new Handler();

    private RecyclerView.LayoutManager mLayoutManager;

    @Override
    public void init() {
        mInflater = LayoutInflater.from(mContext);
        mLayoutManager = new LinearLayoutManager(mContext);
        mDataView.setLayoutManager(mLayoutManager);  //<-- Where the null reference is
    }

    @Override
    public void doWork() {

        WhatsNewAdapter mAdapter = new WhatsNewAdapter();
        mDataView.setAdapter(mAdapter);
        ...

    }

    ...
}

Base.class:

public class Base extends Fragment {

    public View mView;
    public RecyclerView mDataView;
    public ProgressBar mProgressBar;
    public Context mContext;

    public Base() { }

    @Override
    public void onAttach(Activity mActivity) {
        mContext = mActivity;
        init();
        doWork();
    }

    @Override
    public View onCreateView(LayoutInflater _i, ViewGroup _vg, Bundle savedInstanceBundle){
        mView = _i.inflate(R.layout.f_base, null);
        mDataView = (RecyclerView) mView.findViewById(R.id.data);
        mProgressBar = (ProgressBar)mView.findViewById(R.id.loading);
        return mView;
    }

    public void init() { }

    public void doWork() { }

}

I read from here that I should override onAttach(Activity activity) to make sure that the context isn't null, but from the error, it still seems that it is null. Anyone know why I would be getting this error by chance or have a better suggestion on how I should set up my boilerplate fragment? Sorry if the code looks bad, I am trying to learn use fragments better. :)

Upvotes: 0

Views: 903

Answers (2)

Yaroslav Mytkalyk
Yaroslav Mytkalyk

Reputation: 17115

onAttach() is called before onCreateView().

So mDataView is null at init().

I suggest calling init() and doWork() at onViewCreated()

Upvotes: 1

laalto
laalto

Reputation: 152817

Your mDataView has not yet been initialized.

onAttach() is called before onCreateView(). init() where you use mDataView is called before mDataView is initialized in onCreateView().

Postpone the code that needs to access fragment views to onCreateView() or later.

Upvotes: 5

Related Questions