我有一个片段,其中一个函数创建一个 DatabaseHandler 并在对象中调用一个函数:
final DatabaseHandler db = new DatabaseHandler(getActivity());
String teamName = db.getTeamName();
DatabaseHandler 构造函数为:
Context context;
public DatabaseHandler(Context contextPassed) {
super(contextPassed, DATABASE_NAME, null, DATABASE_VERSION);
context = contextPassed;
}
在 db.getTeamName() 里面的某个地方(通过另一个函数)我有:
SQLiteDatabase db = this.getWritableDatabase();//exception here!
这在 99% 的情况下都可以正常工作。但是如果应用程序已经在后台运行了一段时间并且我恢复它,我会收到 NullPointerException。很难复制,因为在这种情况发生之前,应用程序需要在后台运行很长时间。这让我想到了垃圾收集?该过程由广播意图启动 - 不确定这是否相关。我无法真正调试它,因为我无法复制它 - 但是每天早上醒来时我都会测试它并且它崩溃了。这不是开始新一天的好方法,它让我发疯!日志猫:
threadid=1: thread exiting with uncaught exception (group=0x400259f8)
FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=updateSettingsTeamName } in com.gcm.goalpocket.MainActivity$4@4634a608
at android.app.ActivityThread$PackageInfo$ReceiverDispatcher$Args.run(ActivityThread.java:938)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:144)
at android.app.ActivityThread.main(ActivityThread.java:4937)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98)
at com.gcm.goalpocket.DatabaseHandler.getUserID(DatabaseHandler.java:529)
at com.gcm.goalpocket.DatabaseHandler.getTeamName(DatabaseHandler.java:563)
at com.gcm.goalpocket.Settings.setTeamName(Settings.java:310)
at com.gcm.goalpocket.MainActivity$4.onReceive(MainActivity.java:257)