Android問題:報錯Index -1 requested, with a size of 1
使用Cursor使,讀取裡面的資料用到getColumnIndex()時報錯:
Index -1 requested, with a size of 1
仔細閱讀過Cursor的文件,發現關於getColumnIndex()這個方法的說明如下:
public abstract int getColumnIndex (String columnName)
Since: API Level 1
Returns the zero-based index for the given column name, or -1 if the column doesn't exist. If you expect the column to exist use getColumnIndexOrThrow(String) instead, which will make the error more clear.
文件裡清楚的表明:在要讀取的列不存在的時候該方法會返回值“-1”。所以可知,以上報錯可能是因為要get的列不存在,也可能是因為遊標位置不對。後來發現,因為我在執行這個語句前沒有執行“Cursor.moveToNext();”這個函式,導致遊標還位於第一位置的前面,所以索引顯示為“-1”,前面加上這句就沒錯了。
網上另有一種情況是用完Cursor沒有關閉導致報此錯誤,所以也提醒各位用完Cursor要記得執行Cursor.close();
---------------------
作者:hehuanluoluo
來源:CSDN
原文:https://blog.csdn.net/HEHUANLUOLUO/article/details/6231097
版權宣告:本文為博主原創文章,轉載請附上博文連結!