In my app i have a simple Room DataBase with methods like update, insert, delete, and insertOrUpdate which check if same item with primary key exist and just sum it's quantity with new quantity.
The data till now was added by user input, but now the user will be ever able to Sync the data from a remote server, so i've made an API which return the same array of objects as my table is structured, i've done all to get the list in the correct object class but now which would be the best way to use my insertOrUpdate function on that List of objects? should i loop throw each item and add it one by one?
Which would be the best solution to do it?
Here is my code of the DAO:
@Dao
interface ArticoliDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(articolo: Articolo)
@Update
suspend fun update(articolo: Articolo)
@Query("SELECT * FROM articoli_letti_table WHERE barcode = :key")
suspend fun get(key: String): Articolo?
@Query("UPDATE articoli_letti_table SET qta = qta + :qta WHERE barcode = :barcode")
suspend fun updateQuantity(qta: Int, barcode: String)
suspend fun insertOrUpdate(articolo: Articolo) {
val itemFromDB = get(articolo.barcode)
if (itemFromDB == null) {
insert(articolo)
}else {
updateQuantity(articolo.qta, articolo.barcode)
}
}
@Query("DELETE FROM articoli_letti_table WHERE barcode = :key")
suspend fun delete(key: String)
@Query("DELETE FROM articoli_letti_table")
suspend fun clear()
@Query("SELECT * FROM articoli_letti_table")
fun getAll(): Flow<List<Articolo>>
}
And here is my code from SettingActivity where the user can press the button "Sync" where all items from the server should be added to the database:
override fun onPreferenceTreeClick(preference: Preference?): Boolean {
val key = preference?.key
return when (key) {
"sync" -> {
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
val retrofit = Retrofit.Builder()
.baseUrl("http://192.168.100.65/VisualIntelligence/")
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
val service = retrofit.create(ArticoliService::class.java)
val call = service.getArticoli()
call.enqueue(object : Callback<List<Articolo>> {
override fun onResponse(
call: Call<List<Articolo>>,
response: Response<List<Articolo>>
) {
if (response.code() == 200) {
}
}
override fun onFailure(call: Call<List<Articolo>>, t: Throwable) {
Log.e("ERR", t.message.toString())
}
})
Snackbar.make(requireView(), "Sincronizzo gli articoli...", Snackbar.LENGTH_LONG).show()
true
}
else -> true
}
}
insertit asListwhy do you want to insert them one by one? anyway whats your problem?