2016-03-08 47 views
0

我有一個數據庫類用這種方法:訪問SQLite數據庫結果來填充視圖

public Cursor getQuoteById(int qid) 
{ 
    SQLiteDatabase db = this.getReadableDatabase(); 
    String selectQuery = "SELECT * FROM quotes a LEFT JOIN authors b ON b.author_id=a.quote_author WHERE a.quote_id = ?"; 
    Cursor results = db.rawQuery(selectQuery, new String[]{String.valueOf(qid)}); 
    return results; 
} 

在我的活動,我要的是用成績來填充視圖元素。我有這樣的:

Qdb = new DbHelper(this); 
    Cursor results = Qdb.getQuoteById(Integer.parseInt(id)); 
    authorname = (TextView) findViewById(R.id.share_author_name); 
    authorname.setText(results.getString(results.getColumnIndex("first_name"))); 

我得到一個錯誤:

android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

任何人都可以請指出我在做什麼錯?

回答

2

您需要先訪問moveToFirst()才能訪問其數據,並在空結果的情況下檢查返回值。

// e.g. 
if(!cursor.moveToFirst()) 
    return; 
// now access the data 

默認情況下,該查詢返回後,該位置將在-1,第一個數據集之前。