0

I have been searching for an answer to this problem, and found a number of other similar questions. However, I believe I followed the code in the accepted answers and I'm still throwing a NullPointerException error when I try to run it. The question I looked at was this. This was the code suggested for getting a column value from a cursor:

String id = cursor.getString( cursor.getColumnIndex("id") );

The answer made sense to me so I adapted it for my own function:

public String getSubjectId(String subject, String level) {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor subjectCursor = db.rawQuery("SELECT * FROM " + SUBJECTS_TABLE_NAME + " WHERE " + SUBJECTS_COL_2 + " = " + subject + " AND " + SUBJECTS_COL_3 + " = " + level, null);
    String id = subjectCursor.getString(subjectCursor.getColumnIndex("ID"));
    return id;
}

When I run this I am throwing a NullPointerException error. I can't see a problem with the code and am confused about what the error means here. My understanding of the error is that it occurs when a variable is declared but it does not create an object, but I can't see where I have done that in my code. An explanation of what I have done wrong to trigger this error would be much appreciated, as I believe I have followed a number of online tutorials accurately.

Edit: I'm aware of this question but my issue is I can't see a place where I am assigning an object as null so the solution isn't helping me.

Roonil
  • 486
  • 1
  • 4
  • 13
  • Normally, when dealing with `SQL` databases you have to say `while(db.next()){..}`. Or in your case, `subjectCursor.next()`. I don't know if that's the case here. – SedJ601 Jan 14 '18 at 06:43
  • Go [here](https://stackoverflow.com/questions/5457699/cursor-adapter-and-sqlite-example) and look at the answer that starts with `In Android, How to use a Cursor with a raw query in sqlite:`. – SedJ601 Jan 14 '18 at 06:46
  • Also see https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors – Henry Jan 14 '18 at 08:07

0 Answers0