I have a fragment where a function creates a DatabaseHandler and calls a function within the object:
final DatabaseHandler db = new DatabaseHandler(getActivity());
String teamName = db.getTeamName();
with the DatabaseHandler constructor being:
Context context;
public DatabaseHandler(Context contextPassed) {
super(contextPassed, DATABASE_NAME, null, DATABASE_VERSION);
context = contextPassed;
}
Somewhere inside db.getTeamName() (via another function) I have:
SQLiteDatabase db = this.getWritableDatabase();//exception here!
This works fine 99% of the time. But if the app has been in the background for a while and I resume it, I get a NullPointerException. It's tough to replicate because the app needs to be in the background for ages before this happens. It makes me think of garbage collection? The process is started by a broadcast intent - not sure if this is relevant. I can't really debug it because I cant replicate it - but every morning when I wake up I test it and it crashes. Not a good way to start the day and it's driving me nuts! logcat:
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)