所以我的应用程序中有一个db,当应用程序首次通过Helper类打开时,我可以添加(如果只使用dbfavoritosHelper.insert(favId,favName,favType),则会添加; myCursor.requery() ; Tompoo.makeText(getApplicationContext(),“El medio a sido a tus favorite!”在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});
}
欢迎任何建议,谢谢
答案 0 :(得分:1)
您也可以让您的餐桌检查。这是SQLite中的一个例子:
create table foo (
name text unique);
insert into foo (name) values ("Pablo");
insert into foo (name) values ("Pablo"); // Doesn't add row!
因此,如果我们稍微更改插入函数以捕获约束异常并让它返回true / false:
public boolean insert(String mId, String mName, String mType) {
ContentValues cv = new ContentValues();
cv.put("medioId", mId);
cv.put("medioName", mName);
cv.put("medioType", mType);
try {
getWritableDatabase().insertOrThrow("favorito", null, cv);
return true; // Won't be executed if an error is thrown
}
catch(SQLiteConstraintException e) {
return false;
}
}
答案 1 :(得分:0)
我的解决方案是改为
public boolean find(String mId){
Cursor c = getReadableDatabase().rawQuery("SELECT * FROM favorito WHERE favorito.medioId='"+mId+"';", null);
if (c.moveToFirst())
{ return true; }else{
return false;}
}