2013-04-09 129 views
0

我使用Firefox SQLite Manager創建並填充了SQLite數據庫。我將.sqlite文件複製到我的Android項目的資產文件夾中。Android:SQLite數據庫查詢不返回任何記錄

我的目標是使用這些記錄來填充微調器。當我查詢數據庫時,光標顯示列但沒有記錄。

我的DatabaseHandler類延伸SQLiteOpenHelper幷包含方法onCreate,onUpgradegetAllOffices

public List<String> getAllOffices(){ 
    List<String> offices = new ArrayList<String>(); 

    // Select All Query 
    String selectQuery = "SELECT OfficeId as _id, OfficeName FROM " + TABLE_OFFICE; 

    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor cursor = db.rawQuery(selectQuery, null); 

    // looping through all rows and adding to list 
    if (cursor.moveToFirst()) { 
     do { 
      offices.add(cursor.getString(1)); 
     } while (cursor.moveToNext()); 
    } 

    // closing connection 
    cursor.close(); 
    db.close(); 

    // returning offices 
    return offices; 
} 

關於爲什麼不返回記錄的任何想法,將不勝感激。

+2

你確定你已經正確地填充呢? – 2013-04-09 02:59:26

回答

1

試試這個:

public List<String> getAllOffices(){ 
    List<String> offices = new ArrayList<String>(); 

    // Select All Query 
    String selectQuery = "SELECT OfficeId as _id, OfficeName FROM " + TABLE_OFFICE; 

    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor cursor = db.rawQuery(selectQuery, null); 

    // looping through all rows and adding to list 
    if (cursor.moveToFirst()) { 
     do { 
      offices.add(cursor.getString(cursor.getColumnIndex("_id"))); 
     } while (cursor.moveToNext()); 
    } 

    // closing connection 
    cursor.close(); 
    db.close(); 

    // returning offices 
    return offices; 
} 

基本上它只是確保你使用了正確的列索引。否則,如果您使用的是Eclipse,那麼嘗試使用cellobject插件來瀏覽數據庫並確保您的表格已按預期方式填充: http://marketplace.eclipse.org/content/cellobject-sqlite-xml-browser#.UWOU5RaBD3g

+0

感謝您的建議。我發現數據庫沒有按預期填充,儘管當我在SQLite Manager的初始數據庫上運行查詢時,記錄就在那裏。 – marius 2013-04-09 06:35:23

0

請嘗試此操作並可能對您有用。

public List<String> getAllOffices(){ 
    List<String> offices = new ArrayList<String>(); 

    // Select All Query 
    String selectQuery = "SELECT * FROM " + TABLE_OFFICE; 

    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor cursor = db.rawQuery(selectQuery, null); 
    System.out.println("CURSOR SIZE:"+cursor.getCount()) 
    // looping through all rows and adding to list 
    if(cursor.getCount()!=0){ 
     if (cursor.moveToFirst()) { 
      do { 
       System.out.println(cursor.getString(c.getColumnIndex("as per your db column name")); 
      } while (cursor.moveToNext()); 
     } 
    } 

    // closing connection 
    cursor.close(); 
    db.close(); 

    // returning offices 
    return offices; 
} 

所有你必須只看到控制檯輸出,如果你得到正確的那麼首先添加到您的office bean