Search code examples
javaandroidkotlinnullandroid-room

Koltin null check not working for Room TypeConverter function


let's say i have this JSON and you can see that in "Object 1" there is faq array but not in "Object 2" so there for i m checking if its null but after checking null kotlin still run condition body and printing its value to null

[
  {
    "name": "Object 1",
    "faq": [
      {
        "question": "A Question?",
        "answer": "Answer"
      }
    ],
    ...
  },
  {
    "name": "Object 2",
    ...
  },
]

and i am using this code to convert this

class Converters {

    @TypeConverter
    fun faqListToJSON(value: List<FAQ>?): String = Gson().toJson(value)

    @TypeConverter
    fun jsonToFAQ(value: String?): List<FAQ> {

        if(value != null) {

            val faq = object : TypeToken<List<FAQ>>() {}.type

            Log.e("Converter", "jsonToFAQ: $value")

            return Gson().fromJson(value, faq)
        }

        return emptyList()
    }

}

this is my model class of that objects and FAQ object

data class Object(

    ...

    var faq: List<FAQ>? = null
)

data class FAQ(val question: String, val answer: String)

and giving this error log even i have first checked for null

2021-02-02 00:04:13.565 24185-24447/com.burhankhanzada.android.pakistannetworksbundlesoffers.debug E/Converter: jsonToFAQ: null
    Process: com.burhankhanzada.android.pakistannetworksbundlesoffers.debug, PID: 24185
    java.lang.NullPointerException: Gson().fromJson(value, faq) must not be null
        at com.burhankhanzada.android.pakistannetworksbundlesoffers.data.Converters.jsonToFAQ(Converters.kt:29)
        at com.burhankhanzada.android.pakistannetworksbundlesoffers.data.othercodes.OtherCodeDao_Impl$3.call(OtherCodeDao_Impl.java:289)
        at com.burhankhanzada.android.pakistannetworksbundlesoffers.data.othercodes.OtherCodeDao_Impl$3.call(OtherCodeDao_Impl.java:187)

Solution

  • well for this solution my workaround is this as you can see in my entity i have already declared that this field can be null var faq: List<FAQ>? = null so instead check null in TypeConverter just convert it straight like this

    @TypeConverter
    fun jsonToFAQ(value: String) = Gson().fromJson(value, Array<FAQ>::class.java).toList()
    

    and then check null where ever you are using this field