2011-07-21 65 views
4

我正在查看Android SDK中的Notes應用程序示例。我想要學習如何做的是不使用CursorAdapter傳遞給ListAdpater/ListView進行排序,我想知道我可以如何自己處理數據;特別是以ArrayList形式。在這個例子中,一個筆記基本上有一個ID,標題和正文。我想知道如何查詢SQLite數據庫並使用它返回的遊標來收集數據並創建一個對象的對象實例,我將調用Note,它具有id,title和body的參數。我最終希望將所有這些對象存儲到ArrayList中進行管理。我只是不確定如何處理光標。這是一個相當普遍的問題,但我只需要有人指出我朝着正確的方向。獲取SQLite數據庫並將其存儲在一個對象數組中

回答

1

其實我玩了之後想通了自己。所以我意識到使用cursor.getColumnIndex("name_of_column")將返回列索引,以用於cursor.getInt(cursor.getColumnIndex("_id"));等命令。我所要做的只是使用for循環遍歷整個列表,並使用cursor.moveToNext()來遍歷所收集的行。我在發佈這個問題後提出了這個分鐘。 :)

5

我可能沒有得到你的問題,但你需要查詢你的數據庫然後添加遊標數據到ArrayList?

List<String> pointsList = new ArrayList<String>(); 
    database = openOrCreateDatabase("favorites", SQLiteDatabase.OPEN_READWRITE, null); 
    if(database!=null) 
    { 
     c= database.rawQuery(QUERY, null); 
     c.moveToFirst(); 
     while(c.isAfterLast()==false) 
     { 
      pointsList.add(c.getInt(c.getColumnIndex("id")); // do the same for other columns 
      c.moveToNext(); 
     } 

    } 
    database.close(); 
    c.close(); 
0

這可以幫助你,

public ArrayList<ArrayList<Object>> getAllRowsAsArrays() 
    { 
     // create an ArrayList that will hold all the data collected from 
     // the database. 
     ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>(); 

     // This is a database call that creates a "cursor" object. 
     // The cursor object store the information collected from the 
     // database and is used to iterate through the data. 
     Cursor cursor; 

     try 
     { 
      // ask the database object to create the cursor. 
      cursor = db.query(
        TABLE_NAME, 
        new String[]{TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO}, 
        null, null, null, null, null 
      ); 

      // move the cursors pointer to position zero. 
      cursor.moveToFirst(); 

      // if there is data after the current cursor position, add it 
      // to the ArrayList. 
      if (!cursor.isAfterLast()) 
      { 
       do 
       { 
        ArrayList<Object> dataList = new ArrayList<Object>(); 

        dataList.add(cursor.getLong(0)); 
        dataList.add(cursor.getString(1)); 
        dataList.add(cursor.getString(2)); 

        dataArrays.add(dataList); 
       } 
       // move the cursor's pointer up one position. 
       while (cursor.moveToNext()); 
      } 
     } 
     catch (SQLException e) 
     { 
      Log.e("DB Error", e.toString()); 
      e.printStackTrace(); 
     } 

     // return the ArrayList that holds the data collected from 
     // the database. 
     return dataArrays; 
    } 
+0

你可以發佈插件的任何例子? – delive

相關問題