Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

error: Cannot figure out how to read this field from a cursor. Kotlin Android

package petbox.ae.Class

import androidx.room.Entity import androidx.room.PrimaryKey

@Entity(tableName = "products") 
data class PostModel(
    @PrimaryKey val id : Int? = null,
    val images: ArrayList<Data>,
    val name: String,
    val description: String,
    val price: Double?=null ) 

 data class Data(
    val id: Int,
    val date_created: String,
    val date_created_gmt: String,
    val date_modified: String,
    val src: String, )

and the error i am getting is:

error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
private final java.util.ArrayList<petbox.ae.Class.Data> images = null;

error: Type of the parameter must be a class annotated with @Entity or a collection/array of it. retrofit2.Call<java.util.List<petbox.ae.Class.PostModel>> product, @org.jetbrains.annotations.NotNull()

error: Cannot figure out how to read this field from a cursor.

private final java.util.ArrayList<petbox.ae.Class.Data> images = null;

how to make it read it ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need type converter for your List of Data objects.

class DataConverter {

    @TypeConverter
    fun fromListToString(list: List<*>): String {
        val type = object: TypeToken<List<*>>() {}.type
        return Gson().toJson(list, type)
    }

    @TypeConverter
    fun toData(dataString: String?): List<Data> {
        if(dataString == null || dataString.isEmpty()) {
            return mutableListOf()
        }
        val type: Type = object : TypeToken<List<Data>>() {}.type
        return Gson().fromJson(dataString, type)
    }
}

And annotate your images field like this:

@TypeConverters(DataConverter.class)
val images: ArrayList<Data>

Here is documentation https://developer.android.com/training/data-storage/room/referencing-data


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...