2013-01-16 92 views
0

我從使用此代碼數據庫中提取數據:爲什麼我得到空指針異常?

Cursor cursor = db.query(News_Table, null, null, null, null, null, null); 

if (cursor != null) 
{ 
    cursor.moveToFirst(); 
} 
allNews = new News[cursor.getCount()]; 
int i = 0; 

while (!(cursor.isLast())) 
{ 
    allNews[i] = new News(cursor.getInt(0), cursor.getString(2), 
      cursor.getString(1)); 
    cursor.moveToNext(); 
    i++; 
}  

這是我的表的樣子: enter image description here

但每次我的最後一行沒有被提取,我也得到一個空指針異常。這裏是日誌貓屏幕: enter image description here

爲什麼我的代碼只能正確運行n-1行,並在第(n)行有問題,其中n是我的新聞表中的總行數。

+0

您檢查'光標= null',然後三根線以後使用它,如果它不能爲null,與'cursor.getCount()'要麼空校驗!不是必需的,或者你的代碼不能處理空值。 –

回答

4

cursor.isLast()將在遊標位於最後一行時返回true,因此您的while循環將停止在未讀&處處理最後一行的位置。通常用於重複光標將是模式(注意,這不叫moveToFirst()要麼)

Cursor cursor = getACursor(); 
int i = 0; 
while (cursor.moveToNext()) { 
    /// do something with this row 
    allNews[i] = new News(cursor.getInt(0), cursor.getString(2),cursor.getString(1)); 
    i++; 
} 
+1

我同意。 NPE稍後會拋出,可能當作者試圖循環遍歷allNews,但最後一項仍然爲空時。 – Sam

+0

是的,這段代碼有效,但我仍然不明白我的代碼中的缺陷,因爲我使用的代碼在我的應用程序中完全在其他地方工作。那麼爲什麼不在這裏? –

+1

如果你有相同的(!最後)構造,那麼其他地方也是如此,也許這種情況不會打到後來的NPE,所以你沒有注意到。 – superfell

1
while (!(cursor.isLast())) 

我想問題,而不是isLast()。你明確地說,如果不是最後一行。

更改while循環:

while (cursor.moveToNext()) { 
    //Your code. 
}