Вопрос

Are there situations when there is OK to use CRUD tasks against the database on the main thread?

Instead of creating AsyncTask<> class which will deal such task on the background thread.

The reason for this question is reading multiple threads here stating that it's sometimes OK to use main thread for the database tasks. I guess this means estimating how heavy the request will be, but I need clarification there as well.

Does this mean that if I am to enter int or String value (mostly light objects) inside a database, it's not necessary to use background thread for this.

My long-time rule was to use background thread with ALL dealings with a database.

Это было полезно?

Решение

Well It depends on your operations. If any CRUD takes time of less than 2 ms then you can perform them in main thread.And it also depends upon how complex is your query as you said inserting only int or String for which you can perform in main thread but if there multiple rows of same thing then i suggest you to perform it on background threads.But it is always a good practice to perform such database operations using another thread as it will be helpful when you expand your database.

Другие советы

The primary reason to use AsyncTask for IO is to improve the UI responsiveness of your app. If your app is responsive enough without using the AsyncTask, then go ahead. If users of your DB will be saving a lot of data and potentially increasing access times, then it may not be a good idea to do this. If your app ships with a pre-populated DB which won't be enlarged a great deal by users, then it's likely acceptable to forego the AsyncTask.

You have to take into account the scenario where the db can change tomorrow. In that case when your code call getWriteableDatabase(), Android could call onUpdate() and the operation can be very long. So to be sure that future implementation won't break your app you should prefer the use of an AsyncTask.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top