gpt4 book ai didi

android - 将游标数据放入数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:33:26 26 4
gpt4 key购买 nike

作为 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 ( see documentation )。

对于 getString/Int/Long 等,你只需要告诉游标你想要哪一列。如果您不知道 columnIndex,可以使用 cursor.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()]);
}

关于android - 将游标数据放入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18863816/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com