Skip to content Skip to sidebar Skip to footer

Read From A Database In Android To An Arraylist

I'm very new to android development and can't figure out how to read from my database/table into an arrayList. Right now I have: Cursor c = myDB.rawQuery('SELECT * FROM ' +

Solution 1:

Here is a code which shows you how to get ArrayList from Database query.

public ArrayList<String> GetAllValues(String aTable,String[] aColumn)
{
    ArrayList<String> list = new ArrayList<String>();
    Cursor cursor = sqlDB.query(aTable, aColumn, null, null, null, null, null);
    if (cursor.moveToFirst())
    {
        do
        {
            list.add(cursor.getString(0));
        }
        while (cursor.moveToNext());
    }
    if (cursor != null && !cursor.isClosed()) 
    {
        cursor.close();
    }

    returnlist;
}

If you provide null in "aColumn", it will give you all columns. I hope it will help.

Solution 2:

//ArrayList of Calllog class objects
ArrayList<CallLog> arrCallLogs = null;
CursorcurCalllog= myDB.rawQuery("SELECT * FROM " + TableName , null);

            if(curCalllog != null && curCalllog.moveToFirst()) {
            arrCallLogs = newArrayList<CallLog>();
            while (curCalllog.isAfterLast() == false) {
                //Calllog is a class with list of fileds CallLogcallLog=newCallLog();
                callLog.setId(curCalllog.getLong(curCalllog.getColumnIndex(KEY_ROWID)));
                callLog.setName(curCalllog.getString(curCalllog.getColumnIndex(KEY_NAME)));
                callLog.setNumber(curCalllog.getString(curCalllog.getColumnIndex(KEY_NUMBER)));
                callLog.setNumberType(curCalllog.getInt(curCalllog.getColumnIndex(KEY_NUMBERTYPE)));
                callLog.setCallType(curCalllog.getInt(curCalllog.getColumnIndex(KEY_CALLTYPE)));
                callLog.setDatetime(curCalllog.getLong(curCalllog.getColumnIndex(KEY_DATETIME)));
                callLog.setDuration(curCalllog.getLong(curCalllog.getColumnIndex(KEY_DURATION)));
                callLog.set_new(curCalllog.getInt(curCalllog.getColumnIndex(KEY_NEW)));
                arrCallLogs.add(callLog);
                curCalllog.moveToNext();
            }
        }
        curCalllog.close();
    myDB.close();

This is the example how you can make a arrayList from Cursor.

Here there is a class name Calllog which has list of fileds and setter and getter methods. Here i had make a ArrayList of Calllog objects using Cursor

Post a Comment for "Read From A Database In Android To An Arraylist"