仅返回SQLite Select Statement中的Last值

时间:2014-01-10 18:49:18

标签: java android android-sqlite

这里我试图从SQLite中的表中获取所有数据。但每次它返回我的时间只有两次(我的表只包含两行)。

e.g
---------------------+
| Id| name | mobile  |                  
|--------------------|
|1  | abc  | 123456  |
|--------------------|
|2  | xyz  | 789654  |
+--------------------+

我的代码返回:

01-11 00:14:59.291: D/Result:(27629): TID 12274, Name: Tablets , Image: [B@4275d578
01-11 00:14:59.291: D/Result:(27629): TID 12274, Name: Tablets , Image: [B@4275d578

这里我粘贴了我的查询代码:

public List<ProductCategoryDatabaseRetrieve> getProductCategoryData() {
    List<ProductCategoryDatabaseRetrieve> productCategoryDatabaseRetrieve = new ArrayList<ProductCategoryDatabaseRetrieve>();
    ProductCategoryDatabaseRetrieve prodCatDB = new ProductCategoryDatabaseRetrieve();
    SQLiteDatabase sqliteDB = dbHandler.getWritableDatabase();
    String[] columns = { DatabaseHandler._TID,
            DatabaseHandler.TID,
            DatabaseHandler.PRODUCT_CATEGORY_NAME,
            DatabaseHandler.PRODUCT_CATEGORY_IMAGE };
    Cursor cursor = sqliteDB.query(DatabaseHandler.PRODUCT_CATEGORY_TABLE,
            columns, null, null, null, null, null);
    if (cursor.getCount() > 0 && cursor !=null) {
        while (cursor.moveToNext()) {
            prodCatDB.set_tid(cursor.getInt(cursor.getColumnIndex(DatabaseHandler._TID)));
            prodCatDB.setTid(String.valueOf(cursor.getInt(cursor
                    .getColumnIndex(DatabaseHandler.TID))));
            prodCatDB.setProductCategoryName(cursor.getString(cursor
                    .getColumnIndex(DatabaseHandler.PRODUCT_CATEGORY_NAME)));
            prodCatDB.setProductCategoryImage(cursor.getBlob(cursor
                    .getColumnIndex(DatabaseHandler.PRODUCT_CATEGORY_IMAGE)));
            productCategoryDatabaseRetrieve.add(prodCatDB);
    }
    } 
    dbHandler.close();
    return productCategoryDatabaseRetrieve;
}

非常感谢您的考虑。

1 个答案:

答案 0 :(得分:3)

那是因为您在ProductCategoryDatabaseRetrieve prodCatDB = new ProductCategoryDatabaseRetrieve();循环之外实例化while一次,然后在每次循环迭代时替换它的属性值。

ProductCategoryDatabaseRetrieve prodCatDB = new ProductCategoryDatabaseRetrieve();移至while循环内部,如

while (cursor.moveToNext()) {
        ProductCategoryDatabaseRetrieve prodCatDB = new ProductCategoryDatabaseRetrieve();//Instantiate here with each iteration.
        prodCatDB.set_tid(cursor.getInt(cursor.getColumnIndex(DatabaseHandler._TID)));
        prodCatDB.setTid(String.valueOf(cursor.getInt(cursor
                .getColumnIndex(DatabaseHandler.TID))));
        prodCatDB.setProductCategoryName(cursor.getString(cursor
                .getColumnIndex(DatabaseHandler.PRODUCT_CATEGORY_NAME)));
        prodCatDB.setProductCategoryImage(cursor.getBlob(cursor
                .getColumnIndex(DatabaseHandler.PRODUCT_CATEGORY_IMAGE)));
        productCategoryDatabaseRetrieve.add(prodCatDB);
}

此外,在if声明中,cursor != null无用。游标永远不会为null,即使它是cursor.getCount(),也会在到达cursor != null之前抛出空指针异常。删除cursor != null,您不需要它。