Issue
Here's my question: I have an app that needs to make a write operation, on an SQLite database, one time per second, it is better to use an AsyncTask to write data on this database or not?
public void insertData(Data data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues RecordValues = new ContentValues();
RecordValues.put("uid", data.getUid());
RecordValues.put("id_usr", data.getUserId());
RecordValues.put("id_route", data.getIdRoute());
RecordValues.put("lat", data.getLatitude());
RecordValues.put("lng", data.getLongitude());
RecordValues.put("timestamp", data.getTime());
RecordValues.put("privacy", data.getTime());
db.insert("DBNAME", null, RecordValues);
db.close();
}
The DB is implemented by using a SqLiteClass
.
The app makes some heavy tasks, working with live data, web-socket, google map and so on, so I want to optimize on this point.
I don't know if starts an asyncTask one time per second is better or not, i can make a mistake falling in error so we can speak about that.
Thanks in advance.
Solution
Yes, this is recommended to have the database operation in a background thread. You might consider using an AsyncTask
or Handler
to handle the DB operations in a background thread instead of putting this in the main UI thread.
You might be also curious about getting the update on your database on changing or inserting an item to your database table. You might consider, using the content observer to get notified about the content changes in your database table. Please check the LoaderCallbacks
functions.
I have created a project in Github here to demonstrate the database operations using LoaderCallbacks
. However, I have put all the database operations in the UI thread. It is better to handle them inside another thread using AsyncTask
or Handler
.
Answered By - Reaz Murshed
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.