I want to access the database from my service which runs in the background. Is that possible?
Asked
Active
Viewed 8,457 times
4
-
Try this http://stackoverflow.com/questions/7058107/service-accessing-a-database – Ajay Feb 15 '12 at 07:16
-
so my database class should extend SQLiteopenhelper. Otherwise the service cannot access it right? – xyzandroid Feb 15 '12 at 07:18
-
yes , please go through the Article http://www.vogella.de/articles/AndroidSQLite/article.html – Ajay Feb 15 '12 at 07:33
-
but i suggest you to use AsyncTask to access database in background instead of Service – Ajay Feb 15 '12 at 07:41
-
does it has any advantage over service? – xyzandroid Feb 15 '12 at 09:43
-
check this post :: http://stackoverflow.com/questions/6957775/android-asynctask-vs-service – Ajay Feb 15 '12 at 09:50
4 Answers
3
Yes, it is possible to access your database from service. To access database, all you need is Context
which is also available in service.

Duncan Jones
- 67,400
- 29
- 193
- 254

waqaslam
- 67,549
- 16
- 165
- 178
-
-
@channae `Service` extends from `Context`, hence passing `this` or `YourService.this` to where ever it's required will work just fine. – waqaslam May 30 '18 at 09:25
1
Yes it is possible to access the database from a service. All you have to do is, create an object of the database class that extends SqliteOpenHelper, pass the ServiceName.this as the context or else use your application class as the context.
DbHelper db = new DbHelper(ServiceClass.this);
db.performOperations();
db.close();
OR
DbHelper db = new DbHelper(YourApplicationClass.getAppContext());
db.performOperations();
db.close();

Rat-a-tat-a-tat Ratatouille
- 7,109
- 5
- 31
- 41
0
Yes, this is a normal functionality which we Use in application. @Ajay is right.
You can Call a method that access DB from your service class in thread which execute after some seconds.