Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SQLite from Services in Android?

It's sad how hard it is to find a simple line of code that does this "In my opinion".

Anyhow, the problem is I have a program with activities and services "I am new to services".
I can access my SQLite DataBase from activities using

TheDB class:

public TheDB(Context context) {
    this.context = context;
    OpenHelper openHelper = new OpenHelper(this.context);
    this.db = openHelper.getWritableDatabase();
}

And then I can just call the methods, e.g.

myActivity class:

private TheDB db;
bla... bla... bla...
this.db = new TheDB(this);
db.insertSomething(id, name);

TheDB class (method called from myActivity):

public void insertSomething(String id, String name){
    db.execSQL("INSERT into " + farmsTable
+ " (id, name)"
+ " Values "
+ " (" + id + ", '" + name  + "')");
}

ALL I want to be able to do is call TheDB's methods from my service like I do from myActivity.

Do I make a new constructor? Do I change the way I instantiate it?

like image 808
ZiGi Avatar asked Nov 22 '10 03:11

ZiGi


People also ask

Does SQLite run as a service?

With SQLite, there are no other processes, threads, machines, or other mechanisms (apart from host computer OS and filesystem) to help provide database services or implementation. There really is no server.

Is SQLite still used in Android?

SQLite is another data storage available in Android where we can store data in the user's device and can use it any time when required.

How can I retrieve single data from SQLite database in Android?

We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data. This method return the total number of columns of the table.


1 Answers

Just do it in the same way you did it for your activity. The only thing that you need to instantiate TheDB is a context; Activity is a Context as well as Service.

like image 177
Cristian Avatar answered Oct 05 '22 22:10

Cristian