【发布时间】:2019-06-08 18:55:16
【问题描述】:
不幸的是,我能找到的所有解决方案都无法帮助我解决问题。
通过单击按钮,我想为我的数据库表添加一些值,但首先它应该检查该行是否已经存在于我的表中,如果存在,它应该更新该行。
这是我的代码:
主要活动:(只需点击按钮)
ingredient= new Ingredient();
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(int i = 0; i < dataSource.size();i++){
tvname = (TextView) shoppingList.getChildAt(i).findViewById(R.id.tvName);
tvamount = (TextView) shoppingList.getChildAt(i).findViewById(R.id.tvAmount);
String nameTV = tvname.getText().toString();
String amountTV = tvamount.getText().toString();
ingredient.setName(nameTV);
ingredient.setAmount(amountTV);
ingredient.setId(i);
TableIngredient.getInstance(IngredientShopping.this).checkRow(ingredient);
}
数据库表:
public class TableIncredient extends SQLiteOpenHelper {
public static TableIngredient INSTANCE = null;
public static final String DB_NAME = "INGREDIENT_TABLE";
public static final int VERSION = 1;
public static final String TABLE_NAME = "ingredient_table";
public static final String KEY_ID = "ID";
public static final String COL_NAME = "Name";
public static final String COL_AMOUNT = "AMOUNT";
public TableIngredient (Context context) {
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createQuery = "CREATE TABLE " + TABLE_NAME
+ "(" + KEY_ID + " INTEGER PRIMARY KEY, "
+ COL_NAME + " TEXT NOT NULL, "
+ COL_AMOUNT + " INTEGER DEFAULT NULL)";
db.execSQL(createQuery);
}
public boolean checkRow(Ingredient ingredient){
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_NAME,
new String[]{KEY_ID, COL_NAME, COL_AMOUUNT},
KEY_ID + " =? AND " + COL_NAME + " =? AND " + COL_AMOUNT + " =?" ,
new String[]{String.valueOf(ingredient)},
null, null, null, null);
ContentValues values = new ContentValues();
values.put(COL_NAME, ingredient.getName());
values.put(COL_AMOUNT, ingredient.getAmount());
if (c.moveToFirst()){
increseIngredient(ingredient);
return true;
}
else {
long newID = db.insert(TABLE_NAME, null, values);
db.close();
getIngredient(newID);
return false;
}
}
}
这段代码总是使用 else 语句,我不知道为什么会这样。
我希望有人可以帮助我创建一个新行(如果不存在)并更新该行(如果存在)。
【问题讨论】:
-
您可以通过使用此代码来做到这一点。检查这篇文章。 stackoverflow.com/questions/27597922/…
-
@Sobhan 我已经尝试过这段代码,但不幸的是它对我不起作用,问题是,它使用 else 语句作为第一个成分,而对于第二个成分,它使用 if 语句,但它应该对两者都使用 else 语句,如果我再次单击添加按钮,那么它应该使用 if 语句