0

我使用 Firefox SQLite 管理器创建并填充了一个 SQLite 数据库。我将 .sqlite 文件复制到我的 Android 项目的 assets 文件夹中。

我的目标是使用这些记录来填充微调器。当我查询数据库时,光标显示列但没有记录。

我的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; 
}   

任何关于为什么不返回记录的想法将不胜感激。

4

2 回答 2

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

于 2013-04-09T03:18:19.890 回答
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

于 2013-04-09T04:48:02.727 回答