Android:如何创建自定义数组适配器以显示数据库

时间:2016-12-24 06:23:10

标签: android arrays listview android-arrayadapter

我需要帮助在listview中显示数据库中的两个值,我通过数组适配器填充,但默认数组适配器只显示1个值,我想显示两个值。下面是我如何通过db填充数组适配器的代码。

 private void updateUI() {
    ArrayList<String> taskList = new ArrayList<>();
    SQLiteDatabase db = mHelper.getReadableDatabase();
    final Cursor cursor = db.query(TaskContract.TaskEntry.TABLE,
            new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE},
            null, null, null, null, null);

    while (cursor.moveToNext()) {
        int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
        taskList.add(cursor.getString(idx));
    }

        mAdapter = new ArrayAdapter<>(this,
                R.layout.item_todo,
                R.id.task_title,
                taskList);
        mTaskListView.setAdapter(mAdapter);


    cursor.close();
    db.close();
}

1 个答案:

答案 0 :(得分:0)

请尝试以下代码:

  private void updateUI() {
        ArrayList<String> taskList = new ArrayList<>();
        SQLiteDatabase db = mHelper.getReadableDatabase();
        final Cursor cursor = db.query(TaskContract.TaskEntry.TABLE,
                new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE},
                null, null, null, null, null);
    if(cursor.getCount()>0 && cursor.moveToFirst()){
        while (cursor.moveToNext()) {
           int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
        taskList.add(cursor.getString(idx));
        }
    }

            mAdapter = new ArrayAdapter<>(this,
                    R.layout.item_todo,
                    R.id.task_title,
                    taskList);
            mTaskListView.setAdapter(mAdapter);


        cursor.close();
        db.close();
    }