SQLite INNER JOIN抛出NullPointerException

时间:2012-03-05 17:20:38

标签: android sqlite nullpointerexception

我无法理解为什么查询最终会抛出NullPointerException

我的数据库包含两个表。第一个叫TABLE_WORDS的词包含单词;名为TABLE_TRANS的第二个包含翻译。一个词可以有很多翻译。

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 + "));";

我通过单词ID查询翻译,并抛出NPE

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;
}

3 个答案:

答案 0 :(得分:4)

好吧,鉴于你的代码:

Cursor cur = db.rawQuery(query, null); // NullPointer always throws here

这表明db为空。该语句中没有其他解除引用操作 - 因此,除非堆栈跟踪实际在某处显示rawQuery,否则db为空。您没有说明db在哪里被赋予非空值,但这是首先要检查的内容......

顺便说一句,不要在SQL中包含这样的值 - 它是SQL injection attacks的配方。改为使用参数化的SQL。

答案 1 :(得分:1)

在我的情况下,我应该使用

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 + "=?";    

Cursor cur = db.rawQuery(query, new String[] { Integer.toString(idSend) } );

我是对的吗?

答案 2 :(得分:1)

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 + "=?";    

Cursor cur = db.rawQuery(query, new String[] { Integer.toString(idSend) } );

这对我有用: - )