我有一个包含查询结果的游标,该查询返回一个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;
}
答案 0 :(得分:1)
您的光标包含“成分对象”的数据。游标中的数据按照执行查询的表的列顺序进行组织。您可以使用包含ingredient_name和measurment的列的索引号。像这样举例如:
cursor.moveToFirst();
ArrayList<Ingredient> ingredientList = new ArrayList<Ingredient>;
while(cursor.moveToNext())
{
Ingredient ingredient = new Ingredient() ;
ingredient.setName(cursor.getString([index of the column]));
ingredient.setMeasurement(cursor.getInt([index of the column]);
ingredientList.add(ingredient);
}
答案 1 :(得分:1)
尝试从光标中获取值并传递它们,而不是传递光标对象本身。 像这样:
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);
}
}
});