Thirumalai Parthasarathi
Thirumalai Parthasarathi

Reputation: 4671

Accessing database from Broadcast receiver as well as with the app

I have built a simple application that accepts data entered by the user and saves it to the local sqlite database. If wifi connection is available it will transmit the data to a REST service hosted on a remote server.

I have done the above part and it is working pretty fine. If WIFI is not available it will just move on and will expect new data from the user.

When the wifi becomes available, i have registered a broadcast receiver which will hit my database and get the values stored and send them to the remote server.

I would like to know, while the broadcast receiver is trying to query my database, if the user is entering data at the same time and it is being saved in the same database, will it fire a SQLException.

As i recall, only one service can access the SQL instance at a time. If it will pose a problem what shall i do to overcome it. I have looked at ContentProviders, would that be the solution?

I am fairly new to android. Please advice.

Upvotes: 0

Views: 973

Answers (1)

Derek Fung
Derek Fung

Reputation: 8211

You may want to take a look at this.

What are the best practices for SQLite on Android?

For me, I would suggest to always create a ContentProvider together with DatabaseHelper when you need Database, no matter you need to provide your data to external application or not. It is actually not difficult to do, the best reference I used to build my ContentProvider is DeskClock, the official app from Android.

Edit: As a side note, you should consider to create a IntentService to be called by your boardcast receiver to do the work, as broadcast receiver should not be used for long running task, like sending things to server.

BroadcastReceiver#onReceive

When it runs on the main thread you should never perform long-running operations in it (there is a timeout of 10 seconds that the system allows before considering the receiver to be blocked and a candidate to be killed).

Upvotes: 1

Related Questions