Monday, November 18, 2024
Google search engine
HomeLanguagesJavaFix “java.lang.NullPointerException” in Android Studio

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.

Java




import java.util.Scanner;
public class Main
{
    public static void main(String[] args) {
          // we can store null value in to scanner
          // object which has not yet been initialised
        Scanner sc = null;
        System.out.println(sc);
    }
}


Output: 

null

It is also important to note that we cannot directly store a null value in a primitive variable or object as shown below.

Java




import java.util.Scanner;
public class Main
{
    public static void main(String[] args) {
        int i = null;
        System.out.println(i);
    }
}


Output:

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.  

Java




import java.util.Scanner;
public class Main
{
    public static void main(String[] args) {
          // sc is an object of Scanner class
          // which has not been initialised yet
        Scanner sc = null;
           // we are trying to access the reference
           // variable which is not yet initialised
         int input =sc.nextInt();
         System.out.println(input);
    }
}


 Output:

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 accessed which gives a NullPointerException.

textview.setText("Hello world");

The App keeps stopping abruptly

Code

Java




import androidx.appcompat.app.AppCompatActivity;
 
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
         // initialising textview to null
        TextView textview = null;
         
          // accessing the reference variable
        textview.setText("Hello World");
    }
}


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

Code

Java




import androidx.appcompat.app.AppCompatActivity;
 
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        TextView textview = null;
         
        try {
            textview.setText("Hello world");
        }
        catch(Exception e){
            Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();
        }
    }
}


Output:

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. 

Solving the NullPointerException 

TextView with id textview

Code

Java




import androidx.appcompat.app.AppCompatActivity;
 
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        // initialising the Textview using
          // findViewById(R.id.textview) method find
        TextView textview = findViewById(R.id.textview);
 
        try {
            textview.setText("Hello world");
        }
        catch(Exception e){
            Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();
        }
    }
}


Output:

Output after Solving NullPointerException

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.

 

RELATED ARTICLES

Most Popular

Recent Comments