Home > Back-end >  java.lang.NullPointerException: Gson().fromJson(placeJson, Place::class.java) must not be null
java.lang.NullPointerException: Gson().fromJson(placeJson, Place::class.java) must not be null

Time:10-05

I used the following function in my code:

private fun sharedPreferences() = context.getSharedPreferences(
        "sunny_weather",
        Context.MODE_PRIVATE
    )

fun getSavedPlace(): Place {
        val placeJson = sharedPreferences().getString("place","")
        return Gson().fromJson(placeJson, Place::class.java)
    }

but the following error appear

java.lang.NullPointerException: Gson().fromJson(placeJson, Place::class.java) must not be null

i had found a similar question and according to asker's meaning, although his code isn`t similar to mine, he also write the getString function but set the second parameter to null. so his program went wrong, and after changing, his program ran well. but i had set the parameter to "", not null, but it's wrong.

CodePudding user response:

Use "{}" for the default value:

fun getSavedPlace(): Place {
    val placeJson = sharedPreferences().getString("place","{}")
    return Gson().fromJson(placeJson, Place::class.java)
}
  • Related