gpt4 book ai didi

java - 仅返回 SQLite Select 语句中的最后一个值

转载 作者:行者123 更新时间:2023-11-29 05:31:08 25 4
gpt4 key购买 nike

在这里,我试图从 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;
}

非常感谢您的考虑。

最佳答案

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

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 是无用的。游标永远不会为空,即使它是 cursor.getCount() 也会在到达 cursor != null 之前抛出空指针异常。删除 cursor != null,你不需要它。

关于java - 仅返回 SQLite Select 语句中的最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21052079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com