Rak*_*ari 5 android android-cursor android-sqlite
在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;
}
Run Code Online (Sandbox Code Playgroud)
以下给出了以下错误:
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
Run Code Online (Sandbox Code Playgroud)
我试图将光标内的数据提取到一个数组.有人可以帮我实现.
Su-*_*ang 13
names.add(cursor.getString(i));
Run Code Online (Sandbox Code Playgroud)
"i"不是游标行索引,而是列索引.游标已定位到特定行.如果需要重新定位光标.使用cursor.move或moveToXXXX(参见文档).
对于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()]);
}
Run Code Online (Sandbox Code Playgroud)
我希望它对你有用.
public static ArrayList<ModelAgents> SelectAll(DbHelper dbaConnection) {
ArrayList<ModelAgents> Agents_aList = new ArrayList<ModelAgents>();
SQLiteDatabase sqldb = dbaConnection.openDataBase();
Cursor cursor = sqldb.rawQuery("SELECT * FROM Agents", null);
if (cursor != null)// If Cursordepot is null then do
// nothing
{
if (cursor.moveToFirst()) {
do {
// Set agents information in model.
ModelAgents Agents = new ModelAgents();
Agents.setID(cursor.getInt(cursor
.getColumnIndex(TblAgents.ID)));
Agents.setCode(cursor.getString(cursor
.getColumnIndex(TblAgents.CODE)));
Agents.setName(cursor.getString(cursor
.getColumnIndex(TblAgents.NAME)));
Agents_aList.add(Agents);
} while (cursor.moveToNext());
}
cursor.close();
}
sqldb.close();
return Agents_aList;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24921 次 |
| 最近记录: |