I'm trying to fetch data from sqlite database and update a custom recycler view with these data. I've created a method in my Database helper class that returns an ArrayList of items fetched from the database. This is how I expect the method to work:
But this is how the method is working:
Below is the snippet of the method that does the item fetching from the database
public ArrayList<RechargeCard> getCard(){
ArrayList<RechargeCard> list = new ArrayList<>();
RechargeCard card = new RechargeCard();
SQLiteDatabase database = getReadableDatabase();
String query = "SELECT * FROM " + RechargeEntry.TABLE_NAME;
Cursor cursor = database.rawQuery(query, null);
if (cursor.moveToFirst()){
do{
String name = cursor.getString(cursor.getColumnIndexOrThrow(RechargeEntry.NAME_COLUMN));
int price = cursor.getInt(cursor.getColumnIndexOrThrow(RechargeEntry.PRICE_COLUMN));
double quantity = cursor.getDouble(cursor.getColumnIndexOrThrow(RechargeEntry.QUANTITY_COLUMN));
double total = cursor.getDouble(cursor.getColumnIndexOrThrow(RechargeEntry.TOTAL));
card.setName(name);
card.setPrice(price);
card.setQuantity(quantity);
card.setTotal(total);
list.add(card);
} while (cursor.moveToNext());
}
cursor.close();
database.close();
return list;
}
What you code is doing is that it is only updating RechargeCard card = new RechargeCard();
for every iteration that the while loop is doing. You should put RechargeCard card = new RechargeCard();
inside the do while loop so it will create new instances every iteration
public ArrayList<RechargeCard> getCard(){
ArrayList<RechargeCard> list = new ArrayList<>();
SQLiteDatabase database = getReadableDatabase();
String query = "SELECT * FROM " + RechargeEntry.TABLE_NAME;
Cursor cursor = database.rawQuery(query, null);
if (cursor.moveToFirst()){
do{
RechargeCard card = new RechargeCard();
String name = cursor.getString(cursor.getColumnIndexOrThrow(RechargeEntry.NAME_COLUMN));
int price = cursor.getInt(cursor.getColumnIndexOrThrow(RechargeEntry.PRICE_COLUMN));
double quantity = cursor.getDouble(cursor.getColumnIndexOrThrow(RechargeEntry.QUANTITY_COLUMN));
double total = cursor.getDouble(cursor.getColumnIndexOrThrow(RechargeEntry.TOTAL));
card.setName(name);
card.setPrice(price);
card.setQuantity(quantity);
card.setTotal(total);
list.add(card);
}while (cursor.moveToNext());
}
cursor.close();
database.close();
return list;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.