Concurrency in SQLite database

非 Y 不嫁゛ 提交于 2019-12-24 01:39:08

问题


How to achieve concurrency in SQLite database? As per documents it is possible using WAL(Write-Ahead Logging).But, I dont know how to implement it.

In my app I want to read data from db on main thread and at the same time a background thread is writing/inserting some data in the same table. On executing read and write query at same time app stops responding until insertion isn't done. Is concurrency possible in SQLite, and how?


回答1:


You need to use a singleton object of DataBase object. For this purpose you can use ContentProvider. Which is a better option to achieve concurrency.

Here is link for tutorial on ContentProvider http://www.vogella.com/articles/AndroidSQLite/article.html

You can refer the documentation also http://developer.android.com/guide/topics/providers/content-providers.html




回答2:


To enable write-ahead logging, just call enableWriteAheadLogging() in the onConfigure() callback of your SQLiteOpenHelper-derived class.




回答3:


"I want to read data from db on main thread": -> Please never do this. It will hangs your UI until database read call executes. Always do it on background thread.

As per my understanding SQLite handles concurrency itself, so we not need to worry about it.

You can use Content Provider to update database by using it's insert() method. Once insertion completes you can notify all register Content Observer about change in database by using following code in insert() method:

getContext().getContentResolver().notifyChange(uri, null);

For creating, registering and unregistering ContentObserver. Please click here.

Please call all Content Provider related operations from background thread or AsyncQueryHandler. You can know more about AsyncQueryHandler here.

Let me know if more details needed or if it helps :)




回答4:


I completely accept the answer by Nigam Patro, With reference to that I recommend use Greenrobot's GreenDAO with content provider, Singleton approach!!

Why GreenDao ?

  • Maximum performance (probably the fastest ORM for Android).
  • Easy to use APIs.
  • Highly optimized for Android.
  • Minimal memory consumption.
  • Small library size, focus on the essentials, code generator .

More info

Realm also trending ORM with replacement for Sqlite, but I don't use it until they provide support for Content Provider!

Other than that there are many RxJava ported ORM libs available have a look into that once you master some RxJava basics ( toughest thing, time consuming, but it minimizes the coding effort)

I think content provider + with minimized SQLite ORM framowrk + RxJava support will solve the majority of the ORM problems in Android.




回答5:


Try SQLite triggers to write to log before insert, update or delete



来源:https://stackoverflow.com/questions/34409275/concurrency-in-sqlite-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!