Database access from different threads in Android
I have a Service that downloads data开发者_开发问答 from the Internet in AsyncTasks. It parses the data and store it in a db. The Service runs continuously.
There is a change that a Activity attempts to read from the db while the Service is writing to it.
I have a database helper with several methods for writing and reading. Could this cause problems? Potentially trying to open the db from two different threads?
there has been talked and written many books about concurrency problems in db .
But using stackoverflow like a wikipedia i have found some interesting thing:
Sqlite on android lets you access the database from multiple procs for reads, but if you're currently writing from one process, reads and writes from other procs will throw an exception because the first write has a lock on the db.
Then the database is well protected from others threads . The bad news is that you must manage those exceptions , and can be a dirty work if you have a big database (meaning with big many tables with much data exchange)
As long as you're only using one instance of a SQLiteDatabase
, you should be fine. Just make sure to only do your db read/write transactions within your database helper, and no other classes. Any transactions made with the same database object will be synchronized for you automatically.
精彩评论