在这里,我试图从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;
}
非常感谢您的考虑。
这是因为您要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
到达之前引发null指针异常。删除cursor != null
,您不需要它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句