Fix “java.lang.NullPointerException” in Android Studio
Hey Geeks, today we will see what NullPointerException means and how we can fix it in Android Studio. To understand NullPointerException, we have to understand the meaning of Null.
What is null?
“null” is a very familiar keyword among all the programmers out there. It is basically a Literal for Reference datatypes or variables like Arrays, Classes, Interfaces, and Enums. Every primitive data type has a default value set to it(Ex: True and False value for Boolean). Similarly, Reference Datatype Variables have Null value as default if it is not initialized during declaration.
It is also important to note that we cannot directly store a null value in a primitive variable or object as shown below.
Main.java:5: error: incompatible types: cannot be converted to int int i = null; ^ 1 error
What is NullPointerException?
It is a run-time exception that arises when an application or a program tries to access the object reference(accessing methods) which has a null value stored in it. The null value gets stored automatically in the reference variable when we don’t initialize it after declaring as shown below.
Exception in thread "main" java.lang.NullPointerException at Main.main(Main.java:6)
Null Pointer Exception in Android Studio
NullPointerException in Android Studio highlighted in yellow color in the below screenshot
As you can observe from the above picture, it contains a Textview which is initialized to null.
TextView textview = null;
The TextView reference variable(i.e. textview) is accesed which gives a NullPointerException.
Handling the NullPointerException in Android Studio
To Handle the NullPointerException smoothly without making the app crash, we use the “Try – Catch Block” in Android.
- Try: The Try block executes a piece of code that is likely to crash or a place where the exception occurs.
- Catch: The Catch block will handle the exception that occurred in the Try block smoothly(showing a toast msg on screen) without letting the app crash abruptly.
The structure of Try -Catch Block is shown below
Using Try Catch we can catch the exception on the screen
How to fix the NullPointerException?
To avoid NullPointerException we have to initialize the Textview component with the help of findviewbyid( ) method as shown below. The findViewbyId( ) takes the “id” value of the component as the parameter. This method helps locate the component present in the app.
As you can see after initializing the text view component we have solved the NullPointerException. Hence in this way, we can get rid of NullPointerException in Android Studio.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.