2011-07-21 51 views
3

這是我第一次使用數據庫,我不確定這是如何工作的。我做了數據庫,並做了一個查詢,返回一個遊標和...現在什麼?真的是什麼光標?我可以使用它來瀏覽我的數據,還是必須將它放入ArrayList或ListActivity中?在SQLite查詢後如何處理光標?

回答

6

您需要迭代遊標以獲得結果。

使用cursor.moveToFirst()和/或cursor.moveToNext()(帶有一個while循環)。然後,您可以使用getX()方法,如cursor.getInt()cursor.getString()

例如,IR您從您的查詢期待一個結果:

if (cursor.moveToFirst()) { 
    String name = cursor.getString(cursor.getColumnIndex('NAME')); 
    int age = cursor.getInt(cursor.getColumnIndex('AGE')); 
} else { 
    // oops nothing found! 
} 
+0

會這是查看數據庫中有多少記錄是最好的方法? – NoBugs

+0

不,請使用計數。 – aromero

0

根據this link它看起來像您可以通過查詢返回使用類似迭代:

cursor.next(); 

而且搶在位置您正在尋找使用數據:

cursor.getString(0) 
2

首先調用cursor.moveToFirst()。每次調用cursor.moveToNext()時,它都會移動到下一行。確保當你用光標完成時,調用cursor.deactivate(),否則你的日誌貓會出錯。

0

from Developer.android:該接口提供對數據庫查詢返回的結果集的隨機讀寫訪問。

換句話說:查詢返回一組由遊標表示的數據。首先,你需要確保你有一個有效的遊標(非空),然後嘗試將其移動到數據集中的所需位置(使用moveToXXX方法)。爲了獲得遊標指向的數據,使用getXXX方法。完成使用後,請確保近距離呼叫釋放資源。

1

遍歷返回遊標實例

public List<Object[]> cursorToTableRows(Cursor cursor) { 
     List<Object[]> result = new ArrayList<Object[]>(cursor.getCount()); 

     cursor.move(0); 
     cursor.moveToNext(); 
     while (cursor.isAfterLast() == false) { 
      Object[] tableRow = new Object[cursor.getColumnCount()]; 
      for(int i=0; i<cursor.getColumnNames().length; i++) { 
       int columnIndex = cursor.getColumnIndex(cursor.getColumnName(i)); 
       String columnValue = cursor.getString(columnIndex); 
       tableRow[i] = columnValue; 
      } 
      result.add(tableRow); 
      cursor.moveToNext(); 
     } 

     cursor.close(); 

     return result; 
    } 

然後創建所需的對象。

public List<Vehicle> getVehicles() { 
     List<Vehicle> vehicles = new ArrayList<Vehicle>(); 
     Cursor cursor = null; 
     List<Object[]> objects = cursorToTableRows(cursor); 
     for(Object[] row : objects) { 
      int i=0; 
      Vehicle vehicle = new Vehicle(row[i++].toString(), row[i++].toString())); 
      vehicles.add(vehicle) 
     } 
     return vehicles; 
    } 
0

你成功有你光標設置後,您通常會希望顯示以某種形式的視圖。

看一看下面的答案使用光標適配器配對了一個詳細的,但簡單的例子,你的新崛起光標成你想要的XML視圖:

https://stackoverflow.com/a/20532937/293280