2013-04-09 118 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