java.lang.NullPointerException in a RecyclerView


This warning appears to me in a layout where it loads a RecyclerView within onCreate in this line specifically in setLayoutManager


generates the following:


Method invocation 'setLayoutManager' may produce   'java.lang.NullPointerException

And to solve this, he offers me

assert recyclerView != null;

First of all I would like to know why the warning and if the solution is effective. I wait for your ideas. Thanks.

asked by Ashley G. 29.12.2016 в 21:01

1 answer


The error tells you that this method can produce the exception java.lang.NullPointerException .

This exception, as indicated in the documentation, occurs due to the following:

  • Call the instance of a method of a null object.
  • Access or modify a field of a null object.
  • Obtain the null length as if it were an array.
  • Accessing or modifying the null slots as if it were an array.
  • Launch null as if it were a Throwable value (throwaway would be the literal translation but it is a type of Java object to throw exceptions).

Additionally, applications should launch instances of this class to indicate other illegal uses of the null object.

Therefore, what you are indicating is that an exception may occur in your code in which you try to perform some of the above actions on a null object which could end your program.

To keep your backs and that this does not happen, offers a solution. This is so that you protect your code and there are no exceptions that can end your program. What that code really means is that you apply the following:

if(recyclerView != null){

In this way, if the recyclerView is null, it will not execute the setLayoutManager method and, therefore, the exception java.lang.NullPointerException will not occur for this specific case.

answered by 29.12.2016 / 21:26