所以我的应用程序中有一个数据库,当应用程序首次通过 Helper 类打开时构建,我可以添加(如果只使用 dbfavoritosHelper.insert(favId, favName, favType);ourCursor.requery();Toast。 makeText(getApplicationContext(),"El medio a sido a tus favorites!" 在 Agrefav 按钮内,)) 并毫无问题地从中删除项目,但我想要完成的是在按下添加按钮检查的那一刻具有相同 favId 的项目已经存在,所以如果它存在,我不想添加它,因为我不想创建重复项,所以我想更新该项目,到目前为止我拥有的代码在这里不起作用是:
在我的主要活动中
//this is how I call insert
Button Agrefav = (Button) findViewById(R.id.btnFav);
Agrefav.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(arrayOfWebData.isEmpty()){
Toast.makeText(getApplicationContext(),
"No hay medio para agregar a favoritos!",
Toast.LENGTH_LONG).show();
}else{
if(!dbfavoritosHelper.find(favId)){
dbfavoritosHelper.insert(favId, favName, favType);
ourCursor.requery();
Toast.makeText(getApplicationContext(),
"El medio a sido a tus favoritos!",
Toast.LENGTH_LONG).show();
}else{
dbfavoritosHelper.update(favId, favId, favName, favType);
ourCursor.requery();
Toast.makeText(getApplicationContext(),
"El medio se a actualizado en tus favoritos!",
Toast.LENGTH_LONG).show();
}
}
}});
//this is how I call delete
dbfavoritosHelper.delete(delId);
delId=null;
ourCursor.requery();
在我的助手中:
//this is how I insert items to table
public void insert(String mId, String mName, String mType) {
ContentValues cv=new ContentValues();
cv.put("medioId", mId);
cv.put("medioName", mName);
cv.put("medioType", mType);
getWritableDatabase().insert("favorito", null, cv);
}
//this is how I'm trying to find if an item already exists in db, but not working
public boolean find(String mId){
try {
getReadableDatabase().rawQuery("SELECT * FROM favorito WHERE favorito.medioId='"+mId+"';", null);
return true;
} catch (SQLException sqle){
return false;
}
}
//this is how I update items
public void update(String id, String mId, String mName, String mType){
ContentValues cv=new ContentValues();
String[] args={id};
cv.put("medioId", mId);
cv.put("medioName", mName);
cv.put("medioType", mType);
getWritableDatabase().update("favorito", cv, "_id=?", args);
}
//this is how I delete them
public void delete(String id){
getWritableDatabase().delete("favorito", "_id=?", new String[] {id});
}
欢迎任何建议,谢谢