Android 通过IntentService打开数据库时出错,数据库可通过活动访问
我有一个数据库助手类dbHelper,它对数据库执行常规操作。我有一个打开的活动,它使用数据库进行操作。现在我想通过服务编辑数据库。所以我实现了下面的代码,它给出了一个空点异常错误。当我删除onHandleIntent中的所有代码并将其编译成日志时。但我不明白为什么这里会出现零点异常。数据库已存在,因为它已通过活动使用 Logcat在DbHelper.getAllItems()处表示空点异常。我不明白为什么在服务类而不是活动类中应该有异常Android 通过IntentService打开数据库时出错,数据库可通过活动访问,android,database,nullpointerexception,intentservice,Android,Database,Nullpointerexception,Intentservice,我有一个数据库助手类dbHelper,它对数据库执行常规操作。我有一个打开的活动,它使用数据库进行操作。现在我想通过服务编辑数据库。所以我实现了下面的代码,它给出了一个空点异常错误。当我删除onHandleIntent中的所有代码并将其编译成日志时。但我不明白为什么这里会出现零点异常。数据库已存在,因为它已通过活动使用 Logcat在DbHelper.getAllItems()处表示空点异常。我不明白为什么在服务类而不是活动类中应该有异常 public class ItemStateServic
public class ItemStateService extends IntentService {
public static final String C_NAME = "item";
static final String TAG = "ItemStateService";
public ItemStateService() {
super(TAG);
}
protected void onHandleIntent(Intent intent) {
DbHelper dbHelper= new DbHelper (this);
Cursor cursor;
cursor = dbHelper.getAllItems();
int count = 0;
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
count++;
}
Log.d(TAG, "dbHelper launched with item count "+count);
}
}
替换此行:
DbHelper dbHelper= new DbHelper (this);
为此:
DbHelper dbHelper= new DbHelper (ItemStateService.this);
我没有调用db.open()。