Not sure what is causing this, but i am trying request data from the api which includes an array of Message objects. If i print the result to the console, the data is correct apart from Messages=null when i would expect Message to be an array of objects. I can't understand what i've missed?
I'm getting this error:
java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter messages
Could anyone point me in the right direction? Code below for the class:
const val PROFILE_RESPONSE_ID = 0
@Entity(tableName = "profile")
data class ProfileResponse(
val id: Int,
val name: String,
val code: String,
val title: String,
@SerializedName("profile_image")
val profileImage: String,
@SerializedName("background_image")
val backgroundImage: String,
@Embedded(prefix = "messages_")
val messages: ArrayList<Messages>,
) {
@PrimaryKey(autoGenerate = false)
var responseId: Int = PROFILE_RESPONSE_ID
}
Sample JSON:
{
"id": 44,
"name": "Jason",
"code": "jason",
"title": "Jason Scott",
"profile_image": "https://sampleurl.com/sample_profile.jpg",
"background_image": "",
"messages": [
{
"id": 0001,
"message": "Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.",
"timestamp": "Thu, 01 Jan 1970 01:00:00 +0100",
}
{
"id": 0002,
"message": "Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.",
"timestamp": "Thu, 01 Jan 1970 01:00:00 +0100",
}
{
"id": 0003,
"message": "Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.",
"timestamp": "Thu, 01 Jan 1970 01:00:00 +0100",
}
}
Managed to solve this by removing @Embedded as I didn't necessarily need the data in another table, and added a TypeConverter to convert the list into a String and back (This question helped). For reference for anyone else:
TypeConvertor Class
class Convertors {
@TypeConverter
fun listToJson(value: List<Message>?): String {
return Gson().toJson(value)
}
@TypeConverter
fun jsonToList(value: String): List<Message>? {
val objects = Gson().fromJson(value, Array<Message>::class.java) as Array<Message>
val list = objects.toList()
return list
}
}
Then adding the @TypeConverters to my database class.
Database Class
@Database(entities = [ProfileResponse::class], version = 1)
@TypeConverters(Convertors::class)
abstract class MainDatabase: RoomDatabase() {
abstract fun profileResponseDao(): ProfileResponseDao
}