2014-03-18 41 views
0

我在數據庫中有兩列,id和city。如何獲取所有城市數據並在行標識小於3時將其放入字符串中。當行標識小於3時,我在編寫查詢以獲取數據時遇到困難。現在,我的方法獲取所有來自數據庫的數據。謝謝。使用行ID從sqlitedatabase獲取特定數據

String[] columns = new String[]{KEY_ROWID, KEY_CITY}; 
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null); 
String result =" "; 
int iRow = c.getColumnIndex(KEY_ROWID); 

int iCity = c.getColumnIndex(KEY_CITY); 


for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){ 


result = result + c.getString(iCity) + "\n"; 


} 



return result; 

回答

1
String[] columns = new String[]{KEY_ROWID, KEY_CITY}; 

    // "note "rowid" is used in fts tables and "id" in normal tables. 
    // I'm assuming your constant KEY_ROWID chose the correct one. 

    String where = KEY_ROWID + " <= " + 3; 

    Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, where, null, null, null, null); 


    if(!cursor.moveToFirst()){ 
     Log.e("System.out", "cursor is empty"); 
    }else{ 

     int ix_city = cursor.getColumnIndexOrThrow(KEY_CITY); 

     StringBuilder sb = new StringBuilder(); 


     do{ 
      String city = cursor.getString(ix_city); 
      Log.i("System.out", "city name " + city); 

      if(TextUtils.isEmpty(city)) 
        continue; 

      sb.append(city).append("\n"); 
     }while(cursor.moveToNext()); 

     Log.i("System.out", "the entire list " + sb.toString()); 

    } 
+0

字符串其中= KEY_ROWID +「<=」 3; //是有假設被是分號後3,因爲它給了一個錯誤 – artist

+0

我錯過了一個加號,但是存在是假設分號。用加號B/W操作符和3 – NameSpace

+0

更新我用你的代碼,但它似乎是崩潰 – artist