将光标数据放入数组 [英] Putting cursor data into an array

查看:263
本文介绍了将光标数据放入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为Android的新手,我无法处理以下问题:

Being new in Android, I am having trouble dealing with the following:

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;
}

以下内容为我提供了以下错误:

The following gives me the following error:

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

我正在尝试将游标内的数据提取到数组中.有人可以帮我实施吗?

I am trying to extract the data inside the cursor to an array. Can someone help me with the implementation.

推荐答案

names.add(cursor.getString(i));

"i"不是游标行索引,而是列索引.游标已定位到特定行.如果您需要重新定位光标.使用cursor.move或moveToXXXX(请参见文档 ).

"i" is not the cursor row index, it's the column index. A cursor is already positioned to a specific row. If you need to reposition your cursor. Use cursor.move or moveToXXXX (see documentation).

对于getString/Int/Long等,您只需要告诉游标您想要哪一列即可.如果您不知道columnIndex,则可以使用cursor.getColumnIndex("yourColumnName").

For getString/Int/Long etc. you just need to tell the cursor which column you want. If you don't know the columnIndex you can use 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()]);
}

这篇关于将光标数据放入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆