2

I am using the sqlitecursorloader lib from commonsware. I receive GCM messages in an Intentservice and would like to insert an entry into the sqlite database. It should update the listview if the app is open.

I tried using this in the activity where the loader is initialized:

public static void createDbEntry(String Title, String Message) {
    ContentValues values=new ContentValues(2);

    values.put(DatabaseHelper.TITLE, Title);
    values.put(DatabaseHelper.MESSAGE, Message);

    loader.insert("constants", DatabaseHelper.TITLE, values);
  }

and this in the intentservice:

MainActivity.createDbEntry(title,message);

As far as I can tell this works most of the time but if the loader is recycled I get a nullpointer.

Should I initialize a new loader in the intentservice?

Please help, I am new to android development.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • cursorloaders are for loading listviews and such not for loading the database. You could do inserts in asynctask. – danny117 Mar 21 '14 at 16:15

1 Answers1

2

Putting a Loader in a static data member is bad, for any Loader, let alone SQLiteCursorLoader, as you will leak your Activity.

I have also now officially discontinued SQLiteCursorLoader.

Either:

  • Switch to using a ContentProvider and a regular CursorLoader, or

  • Use an event bus (LocalBroadcastManager, Square's Otto, greenrobot's EventBus, etc.) to have your service notify your UI layer to refresh itself based upon your changes

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • @Lorof: I would phrase it as "notify the UI", not "notify the ui thread". And make sure that however you do this, you do not leak activities or fragments, such as making them `static`. Both of my suggested alternatives, implemented properly, should not result in leaks. – CommonsWare Mar 21 '14 at 13:46
  • @Lorof: Call `getWriteableDatabase()` on it and use `insert()` or `execSQL()`. – CommonsWare Mar 21 '14 at 13:48