我正在开发食谱书,但在数据库中为同一食谱保存多种配料时遇到问题。我可以添加一个按钮,在成分EditText和数量EditText中添加线性布局的倍数。 因此,for循环评估每个Layout,它获取当前的成分和数量值,将其保存在(Ingredition.class的)newIngredient实例中。然后将实例插入数据库中,最后,将该实例添加到我的“成分” ArrayList中并关闭数据库。通过调试,我发现所有这些仅适用于for循环的第一次迭代。
for (int d=0; d<countIngredients; d++) {
View childViewIng = parentIngredientLayout.getChildAt(d);
EditText childTextViewI = childViewIng.findViewById(R.id.ingredientsField);
EditText childTextViewQ = childViewIng.findViewById(R.id.quantityField);
childIngredient = childTextViewI.getText().toString();
childQuantity = Integer.parseInt(childTextViewQ.getText().toString());
newIngredient = new Ingredient(childIngredient, childQuantity);
dbHelper.insertIngredient(newIngredient);
ingredients.add(newIngredient);
dbHelper.close();
}
答案 0 :(得分:1)
在您的代码中,您正在for
循环内关闭数据库。
由于这个原因,您的代码将执行第一次迭代,然后关闭数据库,因此由于闭合的数据库连接,下一次迭代将失败。
您应该将dbHeloper.close();
呼叫移到循环之外。
成瘾,您可以将变量移至for循环之外,以提高内存使用率。简而言之:
步骤1:循环后关闭数据库
for (int d=0; d < countIngredients; d++) {
View childViewIng = parentIngredientLayout.getChildAt(d);
EditText childTextViewI = childViewIng.findViewById(R.id.ingredientsField);
EditText childTextViewQ = childViewIng.findViewById(R.id.quantityField);
childIngredient = childTextViewI.getText().toString();
childQuantity = Integer.parseInt(childTextViewQ.getText().toString());
newIngredient = new Ingredient(childIngredient, childQuantity);
dbHelper.insertIngredient(newIngredient);
ingredients.add(newIngredient);
}
//move close method here, outside loop
dbHelper.close();
第2步:优化变量
//move variables here, or wherever you want
View childViewIng = null;
EditText childTextViewI = null;
EditText childTextViewQ = null;
for (int d=0; d < countIngredients; d++) {
//in this way you will create only 1 object, and reuse it every time
childViewIng = parentIngredientLayout.getChildAt(d);
childTextViewI = childViewIng.findViewById(R.id.ingredientsField);
childTextViewQ = childViewIng.findViewById(R.id.quantityField);
childIngredient = childTextViewI.getText().toString();
childQuantity = Integer.parseInt(childTextViewQ.getText().toString());
newIngredient = new Ingredient(childIngredient, childQuantity);
dbHelper.insertIngredient(newIngredient);
ingredients.add(newIngredient);
}
dbHelper.close();
希望这会有所帮助!