我有一个包含查询结果的游标,该查询返回成分名称列表及其来自 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/