2010-12-05 193 views
1

嘿傢伙我目前可以從數據庫中獲取數據到表中,但我堅持使用listview。我的代碼是這個取回所有數據:從數據庫填充列表視圖

public ArrayList<Object> getRowAsArray(long rowID) 
{ 
    // create an array list to store data from the database row. 
    // I would recommend creating a JavaBean compliant object 
    // to store this data instead. That way you can ensure 
    // data types are correct. 
    ArrayList<Object> rowArray = new ArrayList<Object>(); 
    Cursor cursor; 

    try 
    { 
     // 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 = db.query 
     (
       TABLE_NAME, 
       new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO, TABLE_ROW_THREE, TABLE_ROW_FOUR, TABLE_ROW_FIVE, TABLE_ROW_SIX, TABLE_ROW_SEVEN }, 
       TABLE_ROW_ID + "=" + rowID, 
       null, null, null, null, null 
     ); 

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

     // if there is data available after the cursor's pointer, add 
     // it to the ArrayList that will be returned by the method. 
     if (!cursor.isAfterLast()) 
     { 
      do 
      { 
       rowArray.add(cursor.getLong(0)); 
       rowArray.add(cursor.getString(1)); 
       rowArray.add(cursor.getString(2)); 
       rowArray.add(cursor.getString(3)); 
       rowArray.add(cursor.getString(4)); 
       rowArray.add(cursor.getString(5)); 
       rowArray.add(cursor.getString(6)); 
       rowArray.add(cursor.getString(7)); 
      } 
      while (cursor.moveToNext()); 
     } 

     // let java know that you are through with the cursor. 
     cursor.close(); 
    } 
    catch (SQLException e) 
    { 
     Log.e("DB ERROR", e.toString()); 
     e.printStackTrace(); 
    } 

    // return the ArrayList containing the given row from the database. 
    return rowArray; 
} 

我將如何填充到列表視圖請。任何幫助讚賞

回答

2

它比這更容易 - 你甚至不需要創建一個數組列表。

「適配器」是關鍵 - 適配器是列表和數據之間的接口。在你的情況下,你想要一個SimpleCursorAdapter。在Api Demos中有這樣的例子。一探究竟。

您只需將它傳遞給查詢的光標,它就會自動填充您的列表視圖中的數據。

+0

你知道任何教程。我已經看到,但沒有到我需要的類型。我在數據庫中有7行顯示 – Fizzb89 2010-12-05 22:06:44