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

与世无争的帅哥 提交于 2020-01-05 09:35:04

问题


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

回答1:


Try this code

while (cursor.moveToNext()) {

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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/27523669/how-to-add-data-from-an-sqlite-database-into-an-arraylist-android

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