我尝试使用方法来测试数据库中的记录是否存在。
public boolean Exists(/*String _id*/) {
Cursor cursor = mDb.rawQuery("select * from "+ TABLE_USER, null );
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
然后我在
中调用它if ( Exists() ) // do sth;
但是当我跑步时它会强行关闭!
这是我的日志猫:
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): FATAL EXCEPTION: main
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): java.lang.RuntimeException: Unable to start activity ComponentInfo{project.bm/project.bm.GPSTracerActivity}: java.lang.NullPointerException
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1622)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at android.os.Looper.loop(Looper.java:123)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at android.app.ActivityThread.main(ActivityThread.java:3647)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at java.lang.reflect.Method.invokeNative(Native Method)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at java.lang.reflect.Method.invoke(Method.java:507)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at dalvik.system.NativeStart.main(Native Method)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): Caused by: java.lang.NullPointerException
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at project.bm.GPSTracerActivity.Exists(GPSTracerActivity.java:145)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at project.bm.GPSTracerActivity.onCreate(GPSTracerActivity.java:47)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
07-13 15:06:55.961: ERROR/AndroidRuntime(1407): ... 11 more
答案 0 :(得分:0)
看到你没有用mDb对象打开数据库。首先打开数据库,然后运行查询。同时把Cursor相关的代码放在try / catch块中。否则你会强行关闭。