简体   繁体   中英

How to add data from an SQLite Database into an ArrayList (Android)

I'm relatively new to Android and I was making a To-Do List application. I have a database containing a column of tasks. How can I put these tasks into an ArrayList and display it ?

helper = new TaskDBHelper(MainActivity.this);
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.query(TaskContract.TABLE, new String[]{TaskContract.Columns._ID,TaskContract.Columns.TASK}, null, null, null, null, null);

        arrayListToDo = new ArrayList<String>();

arrayAdapterToDo = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayListToDo);

        ListView listViewToDo = (ListView) findViewById(R.id.listViewToDo);
        listViewToDo.setAdapter(arrayAdapterToDo);

Try this code

while (cursor.moveToNext()) {

arrayListToDo.add(cursor.getString(cursor.getColumnIndex("Your column name")));
}

You can get the data in Array list :-

 ArrayList<String> arrayListToDo= new ArrayList<String>(); //your query will returns cursor if (cursor.moveToFirst()) { do { arrayListToDo.add(get you string from cursor); } while (cursor.moveToNext()); } 

now add this aray list to your Adapter.

get list data from database this is only overview

     ArrayList<String> data = databaseObject.GetList();
ListView listViewToDo = (ListView) findViewById(R.id.listViewToDo);
arrayAdapterToDo = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
listViewToDo.setAdapter(arrayAdapterToDo);


      ArrayList<String> GetList()
    {
        ArrayList<String> arrayListtemp= new ArrayList<String>();
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.query(TaskContract.TABLE, new String[]{TaskContract.Columns._ID,TaskContract.Columns.TASK}, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                arrayListtemp.add("");// added your table value from database
            } while (cursor.moveToNext());
        }
        return arrayListtemp;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM