如何将SQLite数据库中的数据添加到ArrayList(Android)

时间:2014-12-17 10:41:22

标签: android sqlite arraylist

我对Android比较陌生,我正在制作待办事项列表应用程序。我有一个包含一列任务的数据库。如何将这些任务放入ArrayList并显示它?

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

3 个答案:

答案 0 :(得分:2)

试试此代码

while (cursor.moveToNext()) {

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

答案 1 :(得分:0)

您可以在数组列表中获取数据: -

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

现在将此aray列表添加到您的适配器。

答案 2 :(得分:0)

从数据库获取列表数据这只是概述

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