我的Android应用程序中有一个超类(WhereWolfActivity),它有一个静态SQLiteDatabaseOpenHelper供所有子类使用。数据库连接在onCreate中打开并在onDestroy中关闭(我会跟踪子类活动打开的数量,以确保仅在销毁应用程序中的最后一个活动时关闭数据库连接)。当用户注销时,它们将被带到欢迎屏幕Activity,而不是WhereWolfActivity的子类,因此数据库连接已关闭。但是,当应用程序注销时,应用程序强制关闭,并且我得到以下logcat输出:
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): FATAL EXCEPTION: main
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): java.lang.RuntimeException: Unable to destroy activity {uk.ac.ic.doc.vmw10.wherewolf/uk.ac.ic.doc.vmw10.wherewolf.activities.Tabs}: java.lang.NullPointerException
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3655)
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3673)
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): at android.app.ActivityThread.access$2900(ActivityThread.java:125)
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): at android.os.Handler.dispatchMessage(Handler.java:99)
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): at android.os.Looper.loop(Looper.java:123)
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): at java.lang.reflect.Method.invokeNative(Native Method)
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): at java.lang.reflect.Method.invoke(Method.java:521)
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): at dalvik.system.NativeStart.main(Native Method)
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): Caused by: java.lang.NullPointerException
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): at uk.ac.ic.doc.vmw10.wherewolf.activities.WhereWolfActivity.onDestroy(WhereWolfActivity.java:119)
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3642)
08-11 02:28:24.858: ERROR/AndroidRuntime(29022): ... 11 more
NullPointerException出现在:dbHelper.close();
为什么尝试关闭数据库会产生空指针异常?
答案 0 :(得分:0)
如果没有看到您的代码,我们无法真正知道原因,但显然您的dbHelper
为空。这与试图关闭它无关。
另一方面,让您的生活更简单,并为您的数据库设置单例类。至于关闭,你真的不需要这样做,只需保持打开状态。当您的进程终止时,将负责关闭数据库。确保关闭所有游标。
类似的东西:
public class MyDbHelper extends SQLiteOpenHelper {
private Context context;
private static MyDbHelper instance;
public static MyDbHelper getInstance(Context context) {
if (instance == null) {
instance = new MyDbHelper(context);
}
return instance;
}
}