Photo by Erik Mclean on Unsplash
Java Lang: Number Format Exception
java.lang.NumberFormatException: For input string: "null"
Table of contents
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
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:
- You trying to read from a string that contains a null value.
- 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.