Search code examples
androidkotlinandroid-room

How to handle the type converter when Json array is empty in kotlin Android


class TotalCaseConverters {
    @TypeConverter
    fun listToJsonString(value: MutableList<Tech>?): String =  Gson().toJson(value)

    @TypeConverter
    fun jsonStringToList(value: String) = Gson().fromJson(value, 
    Array<Tech>::class.java).toList()
}

Error:

java.lang.RuntimeException: Exception while computing database live data. at androidx.room.RoomTrackingLiveData.refreshRunnable$lambda$0(RoomTrackingLiveData.kt:74) at androidx.room.RoomTrackingLiveData.$r8$lambda$PhMGW5zFk4QWazERd2lfEeLZqW0(Unknown Source:0) at androidx.room.RoomTrackingLiveData$$ExternalSyntheticLambda0.run(Unknown Source:2) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:644) at java.lang.Thread.run(Thread.java:1012) Caused by: java.lang.NullPointerException: Gson().fromJson(value, Array::class.java) must not be null at com.averigo.mgmt.models.caseManagement.TotalCaseConverters.jsonStringToList(TotalCase.kt:115)


Solution

  • The fromJson() returns null if json string is null or empty. Therefore you can decide what return value is needed. The first option is set nullable ? to model, dao methods and converter. The second option is return an empty list when the json string is null or empty.

    @ProvidedTypeConverter
    class TotalCaseConverters {
        
        @TypeConverter
        fun listToJsonString(value: MutableList<Tech>?): String {
            return Gson().toJson(value)
        }
    
        @TypeConverter
        fun jsonStringToList(value: String?): List<Tech> {
            val jsonString = if (value.isNullOrEmpty()) {
                "[]" // present empty list in json syntax
            } else {
                value
            }
            return Gson().fromJson(jsonString, Array<Tech>::class.java).toList()
        }
    }