Domanda

Come posso creare una lista Array (la visualizzazione dell'elenco primo alfabeto quando scorrimento) con i dati del cursore?

È stato utile?

Soluzione

Vai attraverso ogni elemento della Cursor, e aggiungere uno per uno al 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));
}

(sostituire WhateverTypeYouWant con qualsiasi tipo si vuole fare un ArrayList di, e WHATEVER_COLUMN_INDEX_YOU_WANT con l'indice di colonna del valore che si desidera ottenere dal cursore.)

Altri suggerimenti

Una correzione rapida: il ciclo sopra salta il primo elemento del cursore. Per includere il primo elemento, utilizzare questo:

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

Anche meglio di @ di imbrizi risposta è questa:

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

moveToNext() restituirà false se non c'è nulla di sinistra, quindi questo riduce la SLOC da pochi, ed è più facile da vedere.

Ancora meglio è quello di ottenere l'indice di colonna al di fuori del ciclo.

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

Questo ha funzionato molto bene per me perché volevo un ArrayList di oggetti:

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();

Basta fare un MyObject POJO e assicurarsi che ha un costruttore.

In Kotlin è possibile utilizzare questa estensione:

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

e usarlo:

val listOfIds = cursor.toList { 
    // create item from cursor. For example get id:
    it.getLong(it.getColumnIndex("_id"))
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top