Reputation: 149
i want to getRawCount from sqlite database in service, but i getting error.
Here's my code on service class :
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)
Upvotes: 1
Views: 91
Reputation: 7870
database_center helper = null;
Cursor cursor;
SQLiteDatabase db = helper.getReadableDatabase();
The variable helper is initialized to null in line 1 and never changed afterwards; obviously line 3 will give null exception, since you called method getReadableDatabase()
on a null object.
Upvotes: 3