I've made my first database in Room using kotlin, i have an insert in my DAO, but when i'm trying to use it in my fragment i get the following error:
Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
How should i do the insert at this point correctly?
The insert is made when the user add data in two edittext and press confirm so i cast the insert in that onClick...
Here is how my DAO looks like:
@Dao
interface ArticoliDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(articolo: Articolo)
@Update
fun update(articolo: Articolo)
@Query("SELECT * FROM articoli_letti_table WHERE barcode = :key")
fun get(key: String): Articolo?
@Query("DELETE FROM articoli_letti_table WHERE barcode = :key")
fun delete(key: String)
@Query("DELETE FROM articoli_letti_table")
fun clear()
@Query("SELECT * FROM articoli_letti_table")
fun getAll(): LiveData<List<Articolo>>
}
And here is how i do my insert in the fragment:
private fun addBarcode(barcode: String, qta: Int) {
if (barcode.isEmpty()) {
txtBarcode.requestFocus()
return
}
db.articoliDao.insert(Articolo(barcode, qta))
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
db = ArticoliDatabase.getInstance(requireContext())
}