Java Lang: Number Format Exception

Photo by Erik Mclean on Unsplash

Java Lang: Number Format Exception

java.lang.NumberFormatException: For input string: "null"

·

2 min read

Introduction

I recently encountered a java.lang.NumberFormatException: For input string: "null" exception when writing an Android program as I was quering data from an API and passing the data to a model class. The code below was the main cause of the error I encountered.

Kotlin



val showRating: String =
               responseJSONObject.getJSONObject("rating").getString("average")

........

if (showRating.toDouble() > 8.8) {
              topRatedArrayList!!.add(
                        ShowDataModel(
                              showImage = showImage,
                              showTitle = showName,
                              showRating = showRating,
                              showId = showId,
                              genresArrayList
                        )
              )
}

The code above produces the following exception when you run the program.

Android Studio Error

Movie Recommender – MainActivity.kt [Movie_Recommender.app.main] 7_13_2022 9_34_43 PM.png

With that, it took a long while before I could figure it out. After thorough research on Google and Stack Overflow, I decided to check for nullity of the string before I could check if the number is greater or not and the code below did the trick.


if (showRating != "null") {

         if (showRating.toDouble() > 8.8) {
                            topRatedArrayList!!.add(
                                    ShowDataModel(
                                        showImage = showImage,
                                        showTitle = showName,
                                        showRating = showRating,
                                        showId = showId,
                                        genresArrayList
                                )
                            )
      }
}

Please check if a string is null before performing any operations on it to ensure that the null pointer exception is avoided.

So basically, if you encounter this issue it probably is as a result of:

  1. You trying to read from a string that contains a null value.
  2. You trying to convert a string to an integer, float or double equivalent yet the string is null, empty or it's not a number.