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

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

问题描述

很难找到一行在我看来"执行此操作的简单代码.

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

数据库类:

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  + "')");
}

我想要做的就是像从 myActivity 一样从我的服务中调用 TheDB 的方法.

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 唯一需要的是上下文;Activity 是一个 Context 以及 Service.

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天全站免登陆