Putting cursor data into an array

后端 未结 5 488
南方客
南方客 2021-02-04 20:57

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

public String[] getContacts(){
    Cursor cursor = getReadableDatabase().rawQuery(\"SELECT          


        
5条回答
  •  半阙折子戏
    2021-02-04 21:03

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

    "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).

    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").

    Your loop should look like this:

    public String[] getContacts(){
        Cursor cursor = getReadableDatabase().rawQuery("SELECT name FROM contacts", null);
        cursor.moveToFirst();
        ArrayList names = new ArrayList();
        while(!cursor.isAfterLast()) {
            names.add(cursor.getString(cursor.getColumnIndex("name")));
            cursor.moveToNext();
        }
        cursor.close();
        return names.toArray(new String[names.size()]);
    }
    

提交回复
热议问题