App crashing when trying to use RecyclerView on android 5.0
This issue usually occurs when no LayoutManager
was provided for the RecyclerView
. You can do it like so:
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
For me, I was having the same issue, the issue was that there was an unused RecyclerView in xml with view gone but I am not binding it to any adapter in Activity, hence the issue. It was solved as soon as I removed such unused recycler views in xml
i.e - I removed this view as this was not called in code or any adapter has been set
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rv_profileview_allactivities"
android:visibility="gone" />
I experienced this crash even though I had the RecyclerView.LayoutManager
properly set. I had to move the RecyclerView
initialization code into the onViewCreated(...)
callback to fix this issue.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_listing, container, false);
rootView.setTag(TAG);
return inflater.inflate(R.layout.fragment_listing, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new ListingAdapter(mListing);
mRecyclerView.setAdapter(mAdapter);
}
In my case it was not connected to 'final', but to the issue mentioned in @NemanjaKovačević comment to @aga answer. I was setting a layoutManager on data load and that was the cause of the same crash. After moving the layoutManager setup to onCreateView of my fragment the issue was fixed.
Something like this:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
...
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler);
mLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLayoutManager);