从 table SQLite 的多个特定列中检索数据

Retrieving data from multiple specific columns from a table SQLite

我正在尝试从 SQLite 中的 table 的多个特定列中检索数据,但使用下面的代码,我不确定为什么,但它没有从两个不同的列中获取数据,而是获取了来自我放入方法中的第一列的数据,即 "spendings" table 的 "budget" 列:-

        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" 都将插入 SQLite 的 "budget" 列中的值。我的目标是将 "budget" 列中的值检索到 "amountfromdb_budget" 中,并将 "foodndrinks" 列中的值检索到 "amountfromdb_foodndrinks" 中。

下面是我的 DatabaseHelper "getLatestAmount" 方法 class :-

    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;
    }

我的 "spendings" table 的结构如下:-

    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";

您没有覆盖获取食物和饮料数量时的光标。所以您仍在使用预算光标。所以将 getLatestAmount 的结果保存到 latestamount.

改变

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);
}