はじめに
Kotlinで、バーコード読み取り機能を使用したAndroidアプリ開発時、
読み込んだ値をローカルのDBに保存する際に起こったエラーと、解決方法を共有したいと思います。
エラー内容
Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
UIスレッドを長時間ロックしてしまう可能性があるため、メインスレッド上でDBへのアクセスはできないようです。
解決方法
依存の追加
まずは、build.gradle に下記を追加します。
app/build.gradle
dependencies {
implementation 'io.reactivex.rxjava2:rxjava:2.1.12'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation 'io.reactivex.rxjava2:rxkotlin:2.2.0'
当該ソースの修正
修正前
SampleRepository.insert(records) // 実行したいDBアクセス処理
修正後
Completable.fromAction {
SampleRepository.insert(records) // 実行したいDBアクセス処理
}.subscribeOn(Schedulers.io()).subscribe()
これでエラーがなくなりました。