How can I create a list Array with the cursor data in Android

假装没事ソ 提交于 2019-12-17 15:27:29

问题


How can I create a list Array (the list display First Alphabet when scroll) with the cursor data?


回答1:


Go through every element in the Cursor, and add them one by one to the 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));
}

(replace WhateverTypeYouWant with whatever type you want to make a ArrayList of, and WHATEVER_COLUMN_INDEX_YOU_WANT with the column index of the value you want to get from the cursor.)




回答2:


One quick correction: the for loop above skips the first element of the cursor. To include the first element, use this:

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



回答3:


Even better than @imbrizi's answer is this:

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

moveToNext() will return false if there isn't anything left, so this reduces the SLOC by a few, and is easier to see.

Even better is to get the column index outside of the loop.

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



回答4:


This one worked really well for me because I wanted an arraylist of objects:

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

Just make a POJO MyObject and make sure it has a constructor.




回答5:


In Kotlin you can use this extension:

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

and use it:

val listOfIds = cursor.toList { 
    // create item from cursor. For example get id:
    it.getLong(it.getColumnIndex("_id"))
}


来源:https://stackoverflow.com/questions/1354006/how-can-i-create-a-list-array-with-the-cursor-data-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!