作为 Android 新手,我在处理以下问题时遇到困难:
public String[] getContacts(){
Cursor cursor = getReadableDatabase().rawQuery("SELECT name FROM contacts", null);
String [] names = {""};
for(int i = 0; i < cursor.getCount(); i ++){
names[i] = cursor.getString(i);
}
cursor.close();
return names;
}
下面给我以下错误:
09-18 10:07:38.616: E/AndroidRuntime(28165): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sqllitetrial/com.example.sqllitetrial.InsideDB}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 5
我正在尝试将光标内的数据提取到数组中。有人可以帮助我实施吗?
names.add(cursor.getString(i));
“i”不是光标的行索引,而是列索引。光标已定位到特定行。如果您需要重新定位光标。使用cursor.move或moveToXXXX(查看文档 http://developer.android.com/reference/android/database/Cursor.html).
对于 getString/Int/Long 等,您只需告诉光标您想要哪一列。如果您不知道可以使用的columnIndexcursor.getColumnIndex("yourColumnName")
.
你的循环应该是这样的:
public String[] getContacts(){
Cursor cursor = getReadableDatabase().rawQuery("SELECT name FROM contacts", null);
cursor.moveToFirst();
ArrayList<String> names = new ArrayList<String>();
while(!cursor.isAfterLast()) {
names.add(cursor.getString(cursor.getColumnIndex("name")));
cursor.moveToNext();
}
cursor.close();
return names.toArray(new String[names.size()]);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)