nazmul
nazmul

Reputation: 435

NullPointerException when adding RecyclerView to Fragment

In my fragment's onCreateView method, I am inflating a layout that contains a RecyclerView. However, when I try to reference the view, I get a NullPointerException at the following line:

mRecyclerView.setLayoutManager(mStaggeredLayoutManager);

What am I doing wrong?

Here is my code:

public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstance){
        final StaggeredGridLayoutManager mStaggeredLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);

        mRecyclerView = (RecyclerView)getActivity().findViewById(R.id.list);
        mRecyclerView.setLayoutManager(mStaggeredLayoutManager);

        mRecyclerView.setHasFixedSize(true); //Data size is fixed - improves performance
        mAdapter = new TravelListAdapter(getActivity());
        mRecyclerView.setAdapter(mAdapter);
        return inflater.inflate(R.layout.start_fragment,container,false);
}

Upvotes: 0

Views: 403

Answers (2)

user3143582
user3143582

Reputation:

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        final StaggeredGridLayoutManager mStaggeredLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
mRecyclerView = (RecyclerView) view.findViewById(R.id.list);
mRecyclerView.setLayoutManager(mStaggeredLayoutManager);
mRecyclerView.setHasFixedSize(true);
mAdapter = new TravelListAdapter(getActivity());
mRecyclerView.setAdapter(mAdapter);
super.onViewCreated(view, savedInstanceState);

        }

this is what I would do

Upvotes: 0

James Davis
James Davis

Reputation: 474

You are doing getActivity.findViewById(), which wouldn't work. You just created the view, but it is not attached to the activity yet. For this to work, you have to find the view in the fragment's view, not the activity's view.

First, inflate the fragment's view, and then do inflatedView.findViewById(R.id.list).

Example:

public View onCreateView(...){
    View inflatedView = inflater.inflate(R.layout.start_fragment, container, false);

    mRecyclerView = (RecyclerView) inflatedView.findViewById(R.id.list);

    return inflatedView;
}

Upvotes: 2

Related Questions