从android中的数据库读取到arraylist

时间:2011-07-28 02:36:29

标签: android sqlite arraylist

我是Android开发的新手,无法弄清楚如何从我的database/table读取到arrayList中。现在我有:

      Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);

       int Column1 = c.getColumnIndex("Field1");
       int Column2 = c.getColumnIndex("Field2");

       // Check if our result was valid.
       c.moveToFirst();
       if (c != null) {
        // Loop through all Results
        do {
         String Name = c.getString(Column1);
         int Age = c.getInt(Column2);
         Data =Data +Name+"/"+Age+"\n";
        }while(c.moveToNext());
       }
       TextView tv = new TextView(this);
       tv.setText(Data);
       setContentView(tv);
      }
      catch(Exception e) {
       Log.e("Error", "Error", e);
      } finally {
       if (myDB != null)
        myDB.close();
      }

如何将其读入arraylist?

2 个答案:

答案 0 :(得分:7)

这是一个代码,向您展示如何从数据库查询中获取ArrayList。

public ArrayList<String> GetAllValues(String aTable,String[] aColumn)
{
    ArrayList<String> list = new ArrayList<String>();
    Cursor cursor = sqlDB.query(aTable, aColumn, null, null, null, null, null);
    if (cursor.moveToFirst())
    {
        do
        {
            list.add(cursor.getString(0));
        }
        while (cursor.moveToNext());
    }
    if (cursor != null && !cursor.isClosed()) 
    {
        cursor.close();
    }

    return list;
}

如果在“aColumn”中提供null,它将为您提供所有列。我希望它会有所帮助。

答案 1 :(得分:5)

//ArrayList of Calllog class objects
ArrayList<CallLog> arrCallLogs = null;
Cursor curCalllog = myDB.rawQuery("SELECT * FROM " + TableName , null);

            if(curCalllog != null && curCalllog.moveToFirst()) {
            arrCallLogs = new ArrayList<CallLog>();
            while (curCalllog.isAfterLast() == false) {
                //Calllog is a class with list of fileds 
                CallLog callLog = new CallLog();
                callLog.setId(curCalllog.getLong(curCalllog.getColumnIndex(KEY_ROWID)));
                callLog.setName(curCalllog.getString(curCalllog.getColumnIndex(KEY_NAME)));
                callLog.setNumber(curCalllog.getString(curCalllog.getColumnIndex(KEY_NUMBER)));
                callLog.setNumberType(curCalllog.getInt(curCalllog.getColumnIndex(KEY_NUMBERTYPE)));
                callLog.setCallType(curCalllog.getInt(curCalllog.getColumnIndex(KEY_CALLTYPE)));
                callLog.setDatetime(curCalllog.getLong(curCalllog.getColumnIndex(KEY_DATETIME)));
                callLog.setDuration(curCalllog.getLong(curCalllog.getColumnIndex(KEY_DURATION)));
                callLog.set_new(curCalllog.getInt(curCalllog.getColumnIndex(KEY_NEW)));
                arrCallLogs.add(callLog);
                curCalllog.moveToNext();
            }
        }
        curCalllog.close();
    myDB.close();

这是如何从Cursor创建arrayList的示例。

这里有一个类名称Calllog,它包含fileds和setter以及getter方法的列表。 在这里,我使用Cursor

制作了一个Calllog对象的ArrayList