Pregunta

¿Cómo puedo crear una matriz de lista (la visualización de la lista primer alfabeto cuando desplazamiento) con los datos del cursor?

¿Fue útil?

Solución

Ir a través de cada elemento en el Cursor, y les agrega uno por uno a la ArrayList.

ArrayList<WhateverTypeYouWant> mArrayList = new ArrayList<WhateverTypeYouWant>();
for(mCursor.moveToFirst(); !mCursor.isAfterLast(); mCursor.moveToNext()) {
    // The Cursor is now set to the right position
    mArrayList.add(mCursor.getWhateverTypeYouWant(WHATEVER_COLUMN_INDEX_YOU_WANT));
}

(reemplace WhateverTypeYouWant con cualquier tipo que desea hacer una ArrayList de, y WHATEVER_COLUMN_INDEX_YOU_WANT con el índice de columna del valor que desea llegar desde el cursor.)

Otros consejos

Una corrección rápida: el bucle anterior salta el primer elemento del cursor. Para incluir el primer elemento, utilice este:

ArrayList<String> mArrayList = new ArrayList<String>();
mCursor.moveToFirst();
while(!mCursor.isAfterLast()) {
     mArrayList.add(mCursor.getString(mCursor.getColumnIndex(dbAdapter.KEY_NAME))); //add the item
     mCursor.moveToNext();
}

Incluso mejor que la respuesta de @ imbrizi es la siguiente:

ArrayList<String> mArrayList = new ArrayList<String>();
while(mCursor.moveToNext()) {
     mArrayList.add(mCursor.getString(mCursor.getColumnIndex(dbAdapter.KEY_NAME))); //add the item
}

moveToNext() devolverá false si no hay nada a la izquierda, así que esto reduce el SLOC por unos pocos, y es más fácil de ver.

Aún mejor es conseguir que el índice de la columna fuera del bucle.

ArrayList<String> mArrayList = new ArrayList<String>();
int columnIndex=mCursor.getColumnIndex(dbAdapter.KEY_NAME)
while(mCursor.moveToNext()) {
     mArrayList.add(mCursor.getString(columnIndex)); //add the item
}

Éste funcionó muy bien para mí porque quería un ArrayList de objetos:

List<MyObject> myList = new ArrayList<String>();
Cursor c = ...

while(c.moveToNext()) {
    myList.add(new MyObject(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getString(cursor.getColumnIndex("column1")), cursor.getInt(cursor.getColumnIndex("column2")));        
}
c.close();

Simplemente haga una MyObject POJO y asegúrese de que tiene un constructor.

En Kotlin puede utilizar esta extensión:

fun <T> Cursor.toList(block: (Cursor) -> T) : List<T> {
    return mutableListOf<T>().also { list ->
        if (moveToFirst()) {
            do {
                list.add(block.invoke(this))
            } while (moveToNext())
        }
    }
}

y utilizarlo:

val listOfIds = cursor.toList { 
    // create item from cursor. For example get id:
    it.getLong(it.getColumnIndex("_id"))
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top