multithreading - Android database best practices? -
what "android way" implement database framework?
the 2 goals:
- it should generic enough "database" can sqlite database or on network.
- it should multi-thread safe. (updated: "thread safe", mean should not run in main ui thread, database calls should not conflict each other, , system should know how communicate results main ui thread.)
- updated: should know configuration changes (like changing phone orientation)
this i've gathered here , android docs:
- use loadermanager querying data.
- create contentprovider (1 & 2 makes thread safe)
- put class between contentprovider , data.
however, creating, updating, , deleting data? far can tell, loadermanager queries. should using asyncqueryhandler?
update: asyncqueryhandler doesn't know configuration changes. i've read fragments may way go. or... i'll have make sure asyncqueryhandler implementation handles configuration changes.
(1) pretty easy: put class between contentprovider , data implements low-level crud. example, 1 class can handle sqlite databases , class same interface can handle google drive backend.
after doing research, here's how can handle (2) , (3) android classes:
- asynctask - unfortunately, asynctask doesn't know configuration changes, have write (and gets ugly).
- headless fragments - fragments without ui. have write own asynctaskloader defeats point. (see here http://blogactivity.wordpress.com/2011/09/01/proper-use-of-asynctask/)
- asynctaskloader - seems way go
loaders designed load data can hack loader handle insertions/update. (you can whatever want in loadinbackground() method.)
the catch before honeycomb, loaders share thread pool excecute requests in parallel. (after honeycomb, loaders execute tasks in sequence.) means not tasks execute after each other not guaranteed execute in order there data consistency issues if don't handle multi-threading correctly.
if have service running in background updates database, you'll still have worry multi-threading in post-honeycomb.
the bottom line there doesn't seem android framework abstracts away problem of "database calls should not conflict each other". have handle on own.
Comments
Post a Comment