简体   繁体   中英

Storing a List<Object> in Android Room database

I am currently retrieving a JSON Object from the web using RetroFit, the JSON Object I am getting is actually a List of Objects. I would like to store that List into a Room database table.

interface currentNewsService {
    @GET("api/feed")
    fun getFeed(
            @Query("amount") amount: Int,
    ): Deferred<currentNewsResponse>

    companion object{

        operator fun invoke(): currentNewsService {

            val okHttpClient = OkHttpClient.Builder().build()
            return Retrofit.Builder().client(okHttpClient)
                    .baseUrl("https://someUrl")
                    .addCallAdapterFactory(CoroutineCallAdapterFactory())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build().create(currentNewsService::class.java)
        }
    }
}

And I created a data class that gives me access to the response from the RetroFit call. I am getting the response from the web, but I am having issues storing a List of Objects in Room.

data class currentNewsResponse(
        val news: List<News>){
}

Here is an example of the table I am creating in Room:

@Entity(tableName = "news", indices = [Index(value = ["newsId"], unique = true)])
data class Feed(
@PrimaryKey
val id: Int
@SerializedName("current_news_id")
val newsId: Int)

Can anyone point me to any relevant documentation or help me out by giving me an example of how you would come about storing a List of Objects?

Room does not allow you to store List of objects directly.

The answer you are looking for is TypeConverter with which you convert your List of objects to a type that Room allows and convert back to List of objects when querying.

You already use Gson . So, serialize/deserialize your data with Gson inside your TypeConverter .

There are so many tutorials regarding how to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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