Search code examples
javaandroidsqliteopenhelper

Writing to database when app is closed


I'm using gcm for chat, and I have an onMessageReceived() method that receives the messages, saves them in the database, and sends a notification to the user.

When the app is running (or paused - running in the background), this is how I store the messages in the database:

private DBHelper mDbHelper;
mDbHelper = new DBHelper(MainApplication.getAppContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();

The method getAppContext() is a static method in my main activity which returns the context.

This all works. I receive a message, save it successfully, and get a notification (when app is running, or in the background).

Problem is when the app is closed. I can't use MainApplication.getAppContext();, because there's no context when the app is closed.

Maybe I should pass the context in some other way?


UPDATE

Eventually I saved messages on server if the app was closed, and when user opens it I fetch'em from server, delete them from there, and save them on user's device. (like a queue pop operation...)

Let me know if there's a better method
see accepted answer...


Solution

  • OK so 1 year later I needed this again and I found the answer:

    Turns out there's a static method in SQLiteOpenHelper which opens the database without context: openDatabase().

    So replace this:

    mDbHelper = new DBHelper(MainApplication.getContext());
    db = mDbHelper.getWritableDatabase();
    

    with this:

    db = SQLiteDatabase.openDatabase("path/to/database.db", null, OPEN_READWRITE);
    

    The static method openDatabase() doesn't need a context so we can call it even when the app is closed.