如何在Android中使用SQLite从服务? [英] How to use SQLite from Services in Android?

查看:100
本文介绍了如何在Android中使用SQLite从服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是可悲的是多么不容易找到code简单的线条,这是否在我看来。

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

总之,问题是我有活动和服务,我是新来的服务的程序。
我可以从活动使用访问我的SQLite数据库

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类:

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类:

myActivity class:

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

TheDB类(方法从myActivity叫):

TheDB class (method called from myActivity):

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

我只希望能够做的就是从我的服务调用TheDB的方法,比如我从myActivity做的。

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?

推荐答案

只要做到这一点的,你这样做是为了你的活动一样。你需要实例 TheDB 是上下文的唯一的事; 活动上下文以及服务

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.

这篇关于如何在Android中使用SQLite从服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆