android:强制关闭时尝试sqlite数据库服务

时间:2014-08-12 16:00:08

标签: android sqlite service

我想在服务中从sqlite数据库获取getRawCount,但是我收到了错误。

这是我的服务类代码:

public int onStartCommand(Intent intent, int flags, int startId) {

    database_center helper = null;
    Cursor cursor;

    SQLiteDatabase db = helper.getReadableDatabase();
    cursor = db.rawQuery("select * from list", null);
    int rawCount = cursor.getCount();

    Toast.makeText(this, "The Service Started. Count  "+rawCount, Toast.LENGTH_LONG).show();

    return START_STICKY;
}

Log Cat:

08-12 22:47:51.421: E/AndroidRuntime(13053): FATAL EXCEPTION: main 08-12 22:47:51.421: E/AndroidRuntime(13053): java.lang.RuntimeException: Unable to start service com.example.belService.theService@416d5818 with Intent { cmp=com.example.belService/.theService }: java.lang.NullPointerException 08-12 22:47:51.421: E/AndroidRuntime(13053): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2575) 08-12 22:47:51.421: E/AndroidRuntime(13053): at android.app.ActivityThread.access$2000(ActivityThread.java:143) 08-12 22:47:51.421: E/AndroidRuntime(13053): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1338) 08-12 22:47:51.421: E/AndroidRuntime(13053): at android.os.Handler.dispatchMessage(Handler.java:99) 08-12 22:47:51.421: E/AndroidRuntime(13053): at android.os.Looper.loop(Looper.java:137) 08-12 22:47:51.421: E/AndroidRuntime(13053): at android.app.ActivityThread.main(ActivityThread.java:4963) 08-12 22:47:51.421: E/AndroidRuntime(13053): at java.lang.reflect.Method.invokeNative(Native Method) 08-12 22:47:51.421: E/AndroidRuntime(13053): at java.lang.reflect.Method.invoke(Method.java:511) 08-12 22:47:51.421: E/AndroidRuntime(13053): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038) 08-12 22:47:51.421: E/AndroidRuntime(13053): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805) 08-12 22:47:51.421: E/AndroidRuntime(13053): at dalvik.system.NativeStart.main(Native Method) 08-12 22:47:51.421: E/AndroidRuntime(13053): Caused by: java.lang.NullPointerException 08-12 22:47:51.421: E/AndroidRuntime(13053): at com.example.belService.theService.onStartCommand(theService.java:48) 08-12 22:47:51.421: E/AndroidRuntime(13053): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2558)

1 个答案:

答案 0 :(得分:3)

database_center helper = null;
Cursor cursor;

SQLiteDatabase db = helper.getReadableDatabase();

变量helper在第1行初始化为null,之后从未改变过;显然,第3行将给出null异常,因为你在空对象上调用了方法getReadableDatabase()