user1760007
user1760007

Reputation: 41

Null Pointer Exception in my BroadcastReceiver class

I want to search a db and toast a specific column on the startup of the phone. The app keeps crashing and getting an exception even though I feel as the code is correct.

@Override
public void onReceive(Context ctx, Intent intent) {
    Log.d("omg", "1");
    DBAdapter do = new DBAdapter(ctx);
    Log.d("omg", "2");
    Cursor cursor = do.fetchAllItems();
    Log.d("omg", "3");
    if (cursor.moveToFirst()) {
        Log.d("omg", "4");
        do {
            Log.d("omg", "5");
            String title = cursor.getString(cursor.getColumnIndex("item"));
            Log.d("omg", "6");
            // i = cursor.getInt(cursor.getColumnIndex("id"));
            Toast.makeText(ctx, title, Toast.LENGTH_LONG).show();

        } while (cursor.moveToNext());
    }
    cursor.close();
}

The frustrating part is that I don't see any of my "omg" logs show up in logcat. I only see when my application crashes.

I get three lines of errors in logcat.

10-19 12:31:11.656: E/AndroidRuntime(1471): java.lang.RuntimeException: Unable to start receiver com.test.toaster.MyReciever: java.lang.NullPointerException
10-19 12:31:11.656: E/AndroidRuntime(1471):     at com.test.toaster.DBAdapter.fetchAllItems(DBAdapter.java:96)
10-19 12:31:11.656: E/AndroidRuntime(1471):     at com.test.toaster.MyReciever.onReceive(MyReciever.java:26)

For anyone interested, here is my DBAdapter fetchAllItems code:

public Cursor fetchAllItems() {
    return mDb.query(DATABASE_TABLE, new String[] { KEY_ITEM, KEY_PRIORITY,
            KEY_ROWID }, null, null, null, null, null);
}

Upvotes: 4

Views: 653

Answers (1)

Sam
Sam

Reputation: 86958

The problem is that mDb is null in fetchAllItems(), you need to initialize mDb before trying to use it.

This just a guess but many DBAdapter designs have an open() method, does yours? If so, you simply need to call it before calling fetchAllItems(). If not, you still need to call mDb = ... somewhere in your adapter.

Upvotes: 2

Related Questions