How to use SQLite from Services in Android?

2019-01-19 06:56发布

问题:

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?

回答1:

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.