因此,我的應用程序中有一個數據庫,當應用程序首次通過Helper類打開時,我可以添加它(如果使用dbfavoritosHelper.insert(favId,favName,favType),則添加; ourCursor.requery(); Toast.makeText(getApplicationContext(),在Agrefav按鈕中,「El medio a sido a tus favorites!」),並從中刪除項目沒有問題,但是我想完成的是在按下添加按鈕的時刻檢查是具有相同的favId已存在的項目,所以如果它不,我不想添加它,因爲我不想創建一個副本,所以我想更新該項目,到目前爲止我的代碼不工作這就是:Android如何檢查我的sqlite數據庫中的重複項?
在我的主要活動//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});
}
任何建議,歡迎,感謝
但是這樣一來就不會發送虛假的回報還是可以嗎? – zvzej
我添加了一個解釋。 – Sam
感謝您解釋它是如何工作的! – zvzej