【问题标题】:How to add data from an SQLite Database into an ArrayList (Android)如何将 SQLite 数据库中的数据添加到 ArrayList (Android)
【发布时间】:2014-12-17 10:41:21
【问题描述】:

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

【问题讨论】:

  • 您可以遍历您的游标并将任务添加到您的 ArrayList 但我建议您查看 CursorAdapters。

标签: android sqlite arraylist


【解决方案1】:

试试这个代码

while (cursor.moveToNext()) {

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-07
        • 2017-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多