[java] App crashing when trying to use RecyclerView on android 5.0

I'm trying to mess with the new RecyclerView and whenever I try to run it, my app immediately crashes. It gives me NullPointerException for trying to access methods from android.support.v7.widget.RecyclerView. I've looked at other posts and saw that most people didn't have compile 'com.android.support:recyclerview-v7:+' but I tried that and it hasn't helped at all. Not really sure what to do at this point, any help would be appreciated. Here the error log: (I would post a picture but I don't have 10 rep yet)

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView$LayoutManager.onMeasure(android.support.v7.widget.RecyclerView$Recycler, android.support.v7.widget.RecyclerView$State, int, int)' on a null object reference
        at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:1764)
        at android.view.View.measure(View.java:17430)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:727)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:463)
        at android.view.View.measure(View.java:17430)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
        at android.view.View.measure(View.java:17430)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
        at android.view.View.measure(View.java:17430)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
        at android.view.View.measure(View.java:17430)
        at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:851)
        at android.view.View.measure(View.java:17430)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
        at android.view.View.measure(View.java:17430)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
        at android.view.View.measure(View.java:17430)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
        at android.view.View.measure(View.java:17430)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
        at android.view.View.measure(View.java:17430)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2560)
        at android.view.View.measure(View.java:17430)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5786)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
        at android.view.Choreographer.doCallbacks(Choreographer.java:580)
        at android.view.Choreographer.doFrame(Choreographer.java:550)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

The answer is


I think the problem in your Adapter. Make sure you have returned ViewHolder in onCreateViewHolder(). Like below:

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v;
    v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_leaderboard, parent, false);
    ViewHolder view_holder = new ViewHolder(v);
    return view_holder;
}

I had similar problem when I test my application on GenyMotion. After restart the device in GenyMotion problem was solved


In my case it was not connected to 'final', but to the issue mentioned in @NemanjaKovacevic 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);

Since LinearLayoutManager is vertical by default, an easier way to do this is:

recyclerView.setLayoutManager(new LinearLayoutManager(context));

If you want to change the orientation you could use this constructor:

public LinearLayoutManager(Context context, int orientation, boolean reverseLayout);

I faced the same issue cause I had the RecyclerView in another layout and not on activity_main.xml.

By searching on some sites I got something and felt like sharing here

  1. Add Id to Include tag in Activity_main.xml

    <include id="includedRecyclerLayout" .... </include>

  2. call this layout before Searching view by ID in MainActivity.java

    `ConstraintLayout includedLayout = findViewById(R.id.inckudedRecyclerLayout);

    RecyclerViewrecyclerview=includedLayout.findViewById(R.id.RECYCLER_VIEW_ID)`;


My problem was in my XML lyout I have an android:animateLayoutChanges set to true and I've called notifyDataSetChanged() on the RecyclerView's adapter in the Java code.

So, I've just removed android:animateLayoutChanges from my layout and that resloved my problem.


I had this problem when using Butterknife , I was using fragment

For Fragment, it should be ButterKnife.bind(this,view);

For Activity ButterKnife.bind(this);


In my case, I added only butterknife library and forget to add annotationProcessor. By adding below line to build.gradle (App module), solved my problem.

    annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'

You need to use setLayoutManager in the RecyclerView#onCreate() method. Before adding recyclerView to a view, it must have the LayoutManager set.

 private RecyclerView menuAsList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    menuAsList = (RecyclerView) findViewById(R.id.recyclerView_mainMenu);
    menuAsList.setLayoutManager(new LinearLayoutManager(Home.this));

}

I was using a Dependency Injection - ButterKnife and this problem arised because I had not binded the view.

So inside onCreate() I just inserted this line:

ButterKnife.bind(this);

My RecyclerView declaration with Dependency Injection:

@BindView(R.id.recyclerview)
RecyclerView recyclerView;

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" />

Recyclerview recylerview = findbyid(R.id.recyclerview) May be you have missed it


If I where you I will do this. onView(withId(android.R.id.list)).perform(RecyclerViewActions.scrollToPosition(3)); android.R.id.list change it to your list id and position will be your position inside your array.


In Gradle implement this library :

implementation 'com.android.support:appcompat-v7:SDK_VER'
implementation 'com.android.support:design:SDK_VER'
implementation 'com.android.support:support-v4:SDK_VER'
implementation 'com.android.support:support-v13:SDK_VER'
implementation 'com.android.support:recyclerview-v7:SDK_VER'

In XML mention like this :

<android.support.v7.widget.RecyclerView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:id="@+id/recyclerView"/>

In Fragment we use recyclerView like this :

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
       View rootView = inflater.inflate(R.layout.YOUR_LAYOUT_NAME, container, false);

       RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        APICallMethod();
        YOURADAPTER = new YOURADAPTER(getActivity(), YOUR_LIST); // you can use that adapter after for loop in response(APICALLMETHOD)
        recyclerView.setAdapter(YOURADAPTER);
        return rootView;
    }

In Activity we use RecyclerView like this :

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.YOUR_LAYOUT_NAME);

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        APICallMethod();
        YOURADAPTER = new YOURADAPTER(ACTIVITY_NAME.this, YOUR_LIST); // you can use that adapter after for loop in response(APICALLMETHOD)
        recyclerView.setAdapter(YOURADAPTER);
   }

if you need horizontal RecyclerView do this :

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(layoutManager);
        APICallMethod();
        YOURADAPTER = new YOURADAPTER(ACTIVITY_NAME.this, YOUR_LIST); // you can use that adapter after for loop in response(APICALLMETHOD)
        recyclerView.setAdapter(YOURADAPTER);

if you want to use GridLayoutManager using RecyclerView use like this :

        RecyclerView recyclerView = findViewById(R.id.rvNumbers);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3)); // 3 is number of columns.
        adapter = new MyRecyclerViewAdapter(this, data);
        recyclerView.setAdapter(adapter);

I had this problem when using Butterknife library. I had:

View rootView = inflater.inflate
                (R.layout.fragment_recipe_detail_view, container, false);
ButterKnife.bind(rootView);

But the correct version is:

View rootView = inflater.inflate
                (R.layout.fragment_recipe_detail_view, container, false);
ButterKnife.bind(this, rootView);

For me the problem was with my activity_main.xml(21) in which the recycleView didn't have an id.

activity_main.xml(21)

 <android.support.v7.widget.RecyclerView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button3"
    tools:listitem="@layout/transaction_list_row" />

activity_main.xml

<android.support.v7.widget.RecyclerView

    android:id="@+id/transac_recycler_view"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button3"
    />

It worked when i added a android:id="@+id/transac_recycler_view" to the activity_main.xml(21) recycleView


I got this issue due to wrong reference of RecyclerView id.

recyclerView = (RecyclerView) findViewById(R.id.rv_followers_list);

to

recyclerView = (RecyclerView) findViewById(R.id.rv_search_list);

using fragment

writing code in onCreateView()

RecyclerView recyVideo = view.findViewById(R.id.recyVideoFag);

using activity

writing code in onCreate() RecyclerView recyVideo = findViewById(R.id.recyVideoFag);


recyclerView =
            (RecyclerView) findViewById(R.id.recycler_view2);

Check with you recycler view ID, pointing to actual recycler view solved my issue


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);
}

For those who are using: implementation 'androidx.recyclerview:recyclerview:1.1.0-beta05'

make sure you are using this in your xml layout

I also experienced a crash when running my app below API 27. Here's a link to the message

Originally, I have created a style to change the font size of my textview inside the recyclerview that's why I created this code below: (I could have just called @dimen when changing the font size based on screen sizes)

Inside style.xml

and added this in my theme

themes.xml

After investigating, I found out that this is the one causing me an error and after removing the style, I no longer experiencing a crash.

I tried all the possible solutions I found here in stack overflow and almost gave up on this, thankfully in my curiosity I thought why not removing the style maybe this causes the crash and then boom the crash is gone.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView

Examples related to android-recyclerview

Failed to resolve: com.android.support:cardview-v7:26.0.0 android CardView background color always white Changing background color of selected item in recyclerview Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView) Simple Android RecyclerView example Android Horizontal RecyclerView scroll Direction Margin between items in recycler view Android How to add a recyclerView inside another recyclerView RecyclerView - Get view at particular position Recyclerview inside ScrollView not scrolling smoothly

Examples related to android-5.0-lollipop

Android changing Floating Action Button color Android Support Design TabLayout: Gravity Center and Mode Scrollable Android statusbar icons color Notification bar icon turns white in Android 5 Lollipop How can I change default dialog button text color in android 5 Lollipop : draw behind statusBar with its color set to transparent Android lollipop change navigation bar color CardView not showing Shadow in Android L App crashing when trying to use RecyclerView on android 5.0 How to change status bar color to match app in Lollipop? [Android]