我试图从SQLite中一个表的多个特定列中检索数据,但下面的代码不确定为什么,而是从两个不同的列中获取数据,而是从我的方法中的第一列(即“支出”表的“预算”列)获取数据:
String temp_category = "budget";
Cursor latestamount = myDb.getLatestAmount(id, temp_category);
if (latestamount.getCount() == 0) {
Toast.makeText(AddExpenses.this, "No amount found !", Toast.LENGTH_LONG).show();
} else {
latestamount.moveToFirst();
amountfromdb_budget = latestamount.getDouble(0);
}
temp_category = "foodndrinks";
myDb.getLatestAmount(id, temp_category);
if (latestamount.getCount() == 0) {
Toast.makeText(AddExpenses.this, "No amount found !", Toast.LENGTH_LONG).show();
} else {
latestamount.moveToFirst();
amountfromdb_foodndrinks = latestamount.getDouble(0);
}使用上面的代码,我的"amountfromdb_budget“和"amountfromdb_foodndrinks”将与amountfromdb_foodndrinks列中的值一起插入。我的目标是将“预算”列中的值检索为"amountfromdb_budget“,将”食品饮料“列中的值检索为"amountfromdb_foodndrinks”。
下面是我DatabaseHelper类中的“DatabaseHelper”方法:
public Cursor getLatestAmount(String id, String category) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor latestamount = db.rawQuery("SELECT "+category+" FROM spendings WHERE id =" +id , null);
return latestamount;
}我的“花销”表的结构如下:
private static final String SPENDING_TABLE = "spendings";
private static final String ID_SPENDING = "id";
private static final String BUDGET = "budget";
private static final String TOTAL_EXPENSES = "total_expenses";
private static final String FOODNDRINKS = "foodndrinks";
private static final String TRAVEL = "travel";
private static final String SHOPPING = "shopping";
private static final String ENTERTAINMENT = "entertainment";
private static final String OTHERS = "others";
private static final String BALANCE = "balance";发布于 2018-10-25 11:38:51
当您获得饮料中的食物数量时,您并没有覆盖光标。因此,您仍然在使用预算光标。因此,将结果从getLatestAmount保存到latestamount。
change
myDb.getLatestAmount(id, temp_category);到
latestamount = myDb.getLatestAmount(id, temp_category);,所以您的代码应该类似于这个
String temp_category = "budget";
Cursor latestamount = myDb.getLatestAmount(id, temp_category);
if (latestamount.getCount() == 0) {
Toast.makeText(AddExpenses.this, "No amount found !", Toast.LENGTH_LONG).show();
} else {
latestamount.moveToFirst();
amountfromdb_budget = latestamount.getDouble(0);
}
temp_category = "foodndrinks";
// the line below is what you needed to change
latestamount = myDb.getLatestAmount(id, temp_category);
if (latestamount.getCount() == 0) {
Toast.makeText(AddExpenses.this, "No amount found !", Toast.LENGTH_LONG).show();
} else {
latestamount.moveToFirst();
amountfromdb_foodndrinks = latestamount.getDouble(0);
}https://stackoverflow.com/questions/52988109
复制相似问题