1

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())
}
Kasper Juner
  • 832
  • 3
  • 15
  • 34
  • [Here](https://stackoverflow.com/a/65645822/9701793) you can find different ways of interacting with Room Db – rahat Jan 19 '21 at 15:32
  • Does this answer your question? [Android Room - simple select query - Cannot access database on the main thread](https://stackoverflow.com/questions/44167111/android-room-simple-select-query-cannot-access-database-on-the-main-thread) – Tenfour04 Jan 19 '21 at 16:01

3 Answers3

0

You should not do database queries on main thread. You should use kotlin coroutines or at least launch a background thread to query db.

But if you want to query db on main thread you can call allowMainThreadQueries() on Room.databaseBuilder().

Rolud
  • 121
  • 1
  • 8
0

Call your database functions with coroutines

CoroutineScope(IO).launch {
    db.articoliDao.insert(Articolo(barcode, qta))
}
Håkon Schia
  • 931
  • 1
  • 7
  • 12
0

Try this using Anko the Jetbrains library, you can use the doAsync{...} method to automatically execute database calls.

implementation 'org.jetbrains.anko:anko-common:0.9'

 doAsync {
    dbHelper.addRecentUser(recentUser)
 }
Dinesh
  • 1,410
  • 2
  • 16
  • 29