Search code examples
androidsqlitearraylistandroid-sqliteandroid-cursor

Copying cursor data into arraylist


I have a query which populates the cursor from the database tables rules, in android sqlite. when I use the getcount on my cursor it shows me 24 which means there are 24 rows in the cursor. what I want is that all the data within cursor should be copied to multidimensional array or arraylist or in other words a copy of the database table into array list.

c = obj_db.rawQuery("select * from rules", null);
int count=c.getCount();
String x= String.valueOf(count);

I want the replica of data as in table in array list in short


Solution

  • Do like this

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

    The important line here is

    mArrayList.add(c.getString(c.getColumnIndex(KEY_NAME))); 
    

    Here I am getting the string from the cursor which is placed at column named KEY_NAME, you can getInt etc depending on your data. Just use the corresponding column names.

    Edit.

    This is an example. You can create a custom List of row type and add data to it like this.

    if (cursor != null && cursor.moveToFirst()) {
                //get columns
                int titleColumn = cursor.getColumnIndex
                        (android.provider.MediaStore.Audio.Media.TITLE);
                int idColumn = cursor.getColumnIndex
                        (android.provider.MediaStore.Audio.Media._ID);
                int artistColumn = cursor.getColumnIndex
                        (android.provider.MediaStore.Audio.Media.ARTIST);
                int albumID = cursor.getColumnIndex
                        (MediaStore.Audio.Media.ALBUM_ID);
                int albumColumn = cursor.getColumnIndex
                        (MediaStore.Audio.Media.ALBUM);
                //add row to list
                do {
                    long thisId = cursor.getLong(idColumn);
                    String thisTitle = cursor.getString(titleColumn);
                    String thisArtist = cursor.getString(artistColumn);
                    String thisAlbum = cursor.getString(albumColumn);
                    String thisAlbumID = cursor.getString(albumID)
                    if (thisAlarm + thisNoti + thisRing==0)
                        arrayList.add(new Row(thisId, thisTitle, thisArtist, thisAlbum, thisAlbumID));
                }
                while (cursor.moveToNext());
                cursor.close();
            }