开发者

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜