Search code examples
javaandroidnullpointerexceptioncursor

Cursor throwing NullPointerException when calling moveToFirst()


I've had a crash report on the Play Store recently that looks like this:

java.lang.NullPointerException
    at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:144)
    at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
    at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:196)
    at android.database.AbstractCursor.moveToFirst(AbstractCursor.java:236)
    at com.myapp.MyActivity(MyActivity.java:283)
    at java.lang.Thread.run(Thread.java:856)

At first I thought it was the cursor being null, but it can't be because I check if it's null before I call moveToFirst()

mCursor = getCursorData();

if (mCursor != null)
    mCursor.moveToFirst(); // Line 283

Can anybody tell me why it is crashing?

Edit:

The code above is pretty much at the start of the method it's inside. This is running inside onConfigurationChanged() so I can update the tabs on the activity with the new set from the cursor.

getCursorData() is a method inside my SQLiteOpenHelper: The reason I'm using rawQuery is due to the actual query using an INNER JOIN. The query itself is fine as it's worked perfect for a couple years without this exception being thrown.

public Cursor getCursorData(long userformid) {
    SQLiteDatabase db = getWritableDatabase();

    return db.rawQuery("SELECT * FROM table WHERE _id=?", new String[]{
        String.valueOf(id)
    });
}

I've now changed my code to check getCount() before calling moveToFirst(). I'm just waiting on the user that was having the issue to update to this new version to see if it has worked or not.


Solution

  • You should check the count of the data first, so use this:

    if(mCursor!=null && mCursor.getCount()>0 ){
        mCursor.moveToFirst();
    }