简体   繁体   English

Android Kotlin - 将 Gson 铸造的 API 数据存储到房间数据库中

[英]Android Kotlin - Storing of Gson casted API data into a Room Database

I am using okhttp to fetch Json data from an API, casting it into Gson for some other purposes, and at the same time, storing of the API data into a Room Database .我正在使用okhttp从 API 获取 Json 数据,将其转换为 Gson 用于其他目的,同时将 API 数据存储到Room Database (It can be storing of the API json data itself, or the casted Gson version) However, I am unsuccessful in this, and hope you could point me to the direction where I am going wrong. (它可以存储 API json 数据本身,也可以是铸造的 Gson 版本)但是,我在这方面没有成功,希望您能指出我出错的方向。

I think i'm missing a typeConverter to convert the data retrieved from API and casted into GSON , to be stored in the Room database .我想我缺少一个typeConverter来转换从 API 检索到的数据并转换为GSON ,以存储在Room database But i'm not sure if i'm correct in this, or if my approach is correct in the first place.但是我不确定我在这方面是否正确,或者我的方法首先是否正确。

Or could it be an issue with the fact that I have an Entities data class , but gsonData is casted into SampleData data class ?或者我有一个Entities data class ,但gsonData被转换为SampleData data class ,这可能是一个问题吗?

DataGetter数据获取器

...
...
...
// this suspend function is run within a coroutine.
private suspend fun APICall(url: String, pageNumber: Int, context: Context){
    val urlRequest = Request.Builder().url(url).build()  // Building of the URL to fetch data
    httpClient.newCall(urlRequest).enqueue(object : Callback {
        // onFailure -> cutting this out to shorten code
        // onResponse is where I am fetching the data and calling put to DB
        override fun onResponse(call: Call, response: Response) {
            val dataString = response.body!!.string()
            val gsonData = gsonResult.fromJson(dataString, SampleData::class.java)
            // Do some other stuffs with gsonData separately. This doesn't return anything to gsonData. 
            putToRoomDb(gsonData, context)  // This will eventually be done via another coroutine.
        }
    }
}

private suspend fun putToRoomDb(sampleData: SampleData, context: Context) {        
    val db = MyOnlyDatabase.getInstance(context)
    db.MyOnlyDao().updateOrInsert(sampleData)
}

Entity实体

@Entity(tableName = "sample_data_code_names")
data class SampleDataEntities(
    @PrimaryKey
    var Code: Int,
    val Name: String,
    val Description: String,
    val Item1: String,
    val Item2: String
) 

Dao

@Dao
interface SampleDataDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun updateOrInsert(sampleDataEntities: SampleDataEntities)
}

Database数据库

@Database(entities = [SampleDataEntities::class], version = 1, exportSchema = false)
abstract class MyOnlyDatabase: RoomDatabase() {
    abstract fun sampleDataDao(): SampleDataDao 

    companion object {  
        @Volatile
        private var instance: MyOnlyDatabase? = null    
        fun getInstance(context: Context): MyOnlyDatabase{
            return instance ?: synchronized(this) {                   
                instance ?: buildDatabase(context).also { instance = it }
            }
        }

        private fun buildDatabase(context: Context): MyOnlyDatabase{
            return Room.databaseBuilder(context, MyOnlyDatabase::class.java, "MyOnlyDatabase.db")
                .fallbackToDestructiveMigration()                   
                .build()                                                     
        }
    }
}

Note : Below is the data class for which gsonData is casted into.注意:下面是gsonData被转换成的data class

data class SampleData(val value: List<SampleDataInfoItems>)
data class SampleDataInfoItems(
    val Code: String,
    val Name: String,
    val Description: String,
    val Item1: BigDecimal,
    val Item2: BigDecimal
)

You are not annotating your fields according to the JSON response that is coming from the server.您没有根据来自服务器的JSON响应来注释您的字段。

data class SampleDataInfoItems(
    @SerializedName("name_this_field_on_json")
    val Code: String,
    @SerializedName("and_so_on_for_all_fields")
    val Name: String,
    val Description: String,
    val Item1: BigDecimal,
    val Item2: BigDecimal
)

Also I think you need the GsonConververFactory for Retrofit.另外我认为你需要GsonConververFactory进行改造。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM