1
0

More than 3 years have passed since last update.

KotlinでAndroidアプリ開発時、ローカルのDBに保存処理を行った際に起こったエラーと対策

Posted at

はじめに

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()

これでエラーがなくなりました。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0