I can’t understand why the query ends up throwing a NullPointerException.
My database contains two tables. The first one called TABLE_WORDS contains words; the second one called TABLE_TRANS contains the translations. One word can have many translations.
public static final String CREATE_TABLE_WORDS = "CREATE TABLE " + TABLE_WORDS +
" (" + WORDS_ID + " INTEGER PRIMARY KEY, " + WORDS_WORD +
" TEXT);";
public static final String CREATE_TABLE_TRANS = "CREATE TABLE " + TABLE_TRANS +
" (" + TRANS_ID + " INTEGER PRIMARY KEY, " +
TRANS_WORD + " TEXT, " +
TRANS_FOREIGN_ID_WORD + " INTEGER, " +
"FOREIGN KEY (" + TRANS_FOREIGN_ID_WORD + ") REFERENCES " + TABLE_WORDS + "(" + WORDS_ID + "));";
I query translations by a word ID, and an NPE is thrown.
public Cursor queryTransesByWord(int idSend) {
String query = "SELECT " + DbHelper.TABLE_WORDS + "." + DbHelper.WORDS_WORD + ", " +
DbHelper.TABLE_TRANS + "." + DbHelper.TRANS_WORD +
" FROM " + DbHelper.TABLE_WORDS +
" INNER JOIN " + DbHelper.TABLE_TRANS +
" ON " + DbHelper.TABLE_WORDS + "." + DbHelper.WORDS_ID + "=" +
DbHelper.TABLE_TRANS + "." + DbHelper.TRANS_FOREIGN_ID_WORD + " WHERE " +
DbHelper.TABLE_WORDS + "." + DbHelper.WORDS_ID + "="+ idSend;
Cursor cur = db.rawQuery(query, null); // NullPointer always throws here
if (cur != null)
cur.moveToFirst();
else
Log.e(Constants.LOG_TAG, Constants.DB_ADAPTER_CLASS_NAME_SEP + "queryTransesByWord cursor is null");
return cur;
}
Well, given your code:
That suggests that
dbis null. There’s no other dereferencing operation in that statement – so unless the stack trace actually showsrawQueryin it somewhere, thendbis null. You haven’t given any indication of wheredbis meant to be assigned a non-null value, but that’s the first thing to check…As an aside, please don’t include values in your SQL like that – it’s a recipe for SQL injection attacks. Use parameterized SQL instead.