When should I do certain SQLite operations on another thread(not the main thread)?

前端 未结 3 408
情歌与酒
情歌与酒 2020-12-01 05:05

My Android application includes an SQLite database with an SQLiteOpenHelper class to help manage it. During application use, the user may perform some operatio

相关标签:
3条回答
  • 2020-12-01 05:47

    General rule for everything: If it's fast enough, do it on the main thread. If not, use a worker thread.

    Unless you have a ridiculously huge database, a single operation almost never warrants a separate thread. Databases in general are designed to scale well, but of course a very big database (10,000+ rows?) will be a bit slower than a small one. 30 rows, however, is nothing.

    I would start threading stuff if you have a lot of operations going on, like a bunch of queries, or complicated queries that span several tables.

    As with everything - profile your app, and if it's too slow, optimize. Don't write an awesome synchronized super-duper multi-core-ready database handler if none of your queries takes longer than 2ms.

    0 讨论(0)
  • 2020-12-01 05:48

    Always measure before you optimize!

    Make sure that DB operations you do affect user experience and than start looking for a solution.

    If database stuff gets slow, then use AsyncTask, which was designed to perform tasks in the background, and then update the GUI on EDT.

    0 讨论(0)
  • 2020-12-01 05:53

    There is absoulutely not reason to use a thread here. Just return the cursor, extract the information from the cursor and return it to the main activity.

    Specifically speaking a thread is something ideally that is going to repeat until something happens or it times out. Since the database you are using i'm assuming is on the phone, it would take practically zero time to access it.

    Also another thing you can do is create a Utility class to assist with your activity to database interaction. It would be what your activity calls to interact with the database. Specifically the flow of control would be like this:

    Activity -> Utility -> Database

    Its between the activity and the database to keep them isolated from each other and make it much easier to access whatever it needs since it doesn't have to go directly to the database itself.

    0 讨论(0)
提交回复
热议问题