Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to access an SQLiteDatabase in an AsyncTask?

Is it necessary or even good practice to always access an SQLiteDatabase from an AsyncTask?

Doing it from the UI thread seems to cause no problems and is much simpler to implement.

like image 570
ᅙᄉᅙ Avatar asked Oct 23 '12 18:10

ᅙᄉᅙ


People also ask

What is the use of AsyncTask in android?

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

Which method is used to start the background thread of AsyncTask?

The following code snippet must be present in the MainActivity class in order to launch an AsyncTask. MyTask myTask = new MyTask(); myTask. execute(); The execute method is used to start the background thread in the excerpt above, where we've used a sample class name that extends AsyncTask.

What is SQLiteOpenHelper?

SQLiteOpenHelper class is used for database creation and version management. For performing any database operation, you have to provide the implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.


3 Answers

It is recommended to not perform IO from your main application thread, but, it does not have to be done using an AsyncTask.

You have other options for getting out of your main thread too, some of which include the Loader Framework, IntentService, and Executors.

like image 130
wsanville Avatar answered Oct 10 '22 09:10

wsanville


It's good practice. Database operations aren't always quick, so Android recommends doing all database and network operations on a background thread (AsyncTask, Runnable, etc).

like image 40
toadzky Avatar answered Oct 10 '22 11:10

toadzky


No, it is not necessary to ALWAYS access your database in another thread. It depends on how long it takes. Usually reads / writes are fast, do not slow down the UI, and do not require another thread. However, when performing lengthy operations like cleanups etc. then yes, it is a good idea to do them in another thread.

like image 36
Yar Avatar answered Oct 10 '22 11:10

Yar