android - 使用游标从 SQLite 中扣除值

标签 android sqlite

我有一个包含查询结果的游标,该查询返回成分名称列表及其来自 SQLite 数据库的相应测量值。

我正在尝试实现一个函数,该函数会在按下按钮时从另一个表中扣除这些值。

我在尝试使用游标值实现此功能时遇到了一些问题。我可以只将光标传递到函数中,还是应该将光标放入列表中,然后将列表变量传递到函数中?

下面是我到目前为止的代码,但如果有人能指出我正确的方向,那就太好了。

光标

   final Cursor ingredients = adapter.getRecipesIngredients(recipeCode);

getRecipeIngredients 函数

public Cursor getRecipesIngredients(int code)
{
    return db.rawQuery("select _id, ingredient_name, measurement from ingredients where recipe_code = " + code, null);

}

带功能的按钮代码

    Button cookButton = (Button) findViewById(R.id.cookButton);
    cookButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            while (ingredients.moveToNext())
            {
                String ingredient = ingredients.getString(0);
                String measurement = ingredients.getString(1);
                int i = Integer.parseInt(measurement);
                adapter.deductIngredient(ingredient, i);
            }
        }
    });

更新表的SQL函数

//deducting ingredients after cooking
public boolean deductIngredient(String ingredient, int measurement)
{
    db.rawQuery("update kitchen set kitchen.measurement = kitchen.measurement - "+measurement+" where kitchen.ingredient_name = "+ingredient, null);
    return true;
}

最佳答案

尝试从游标中获取值并传递它们,而不是传递游标对象本身。 像这样:

Button cookButton = (Button) findViewById(R.id.cookButton);
cookButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        while (ingredients.moveToNext())
        {
            String ingredient = ingredients.getString(ingredients.getColumnIndex("ingredient_name"));
            //If you are storing measurement as int
            int measurement = ingredients.getInt(ingredients.getColumnIndex("measurement"));
            //If you are storing measurement as varchar
            //int measurement = Integer.parseInt(ingredients.getString(ingredients.getColumnIndex("measurement")));
            adapter.deductIngredient(ingredient, measurement);
        }
    }
});

关于android - 使用游标从 SQLite 中扣除值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35070877/

相关文章:

android - 根据sqlite中的日期检索条目时出错

java - 以相同的方法读取 SQLite 数据或以相同的方法从两个表中读取数据

java - Sqlite日历重复事件逻辑

android - TextView多行

java - 添加 jar 文件后的 Android Studio preDexDebug

android - 设置宽度时我的自定义对话框没有出现

android - 在 Android 上创建 SSL 连接时出现 SSLPeerUnverifiedException

Android Studio增量混淆导致错误: cannot find symbol class

Android GreenDao 根据条件更新单个字段

database - SQLITE 使用 ORDER BY 时速度极慢