我正在使用SQLite数据库存储来自recyclerview的一些值/项,这些值/项是长按来自Firebase的。在那个recyclerview中,我正在更改已经存储在SQLite数据库中的值/项目的背景。但是问题是,当我长按任何一个项目时,它也会在recyclerview中为每个第21个项目着色。然后在滚动到顶部时为任意随机项着色。
OnBindView
holder.Card.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (favDB.isFav(model.getUrl(), model.getName())) {
Toast.makeText(getContext(), "Already in Favorite", Toast.LENGTH_SHORT).show();
} else {
new FavDB(getContext()).addToFav(
model.getName(), model.getType(), model.getUrl(),
model.getBrowser(), model.getImage());
holder.Card.setCardBackgroundColor(R.color.Background);
Toast.makeText(getContext(), "Added to Favorite", Toast.LENGTH_SHORT).show();
}
return true;
}
});
if (favDB.isFav(model.getUrl(), model.getName())) {
try {
Toast.makeText(getContext(), "Coloring", Toast.LENGTH_SHORT).show();
holder.Card.setCardBackgroundColor(R.color.Background);
favDB.close();
}catch (Exception e){
Toast.makeText(getContext(), "Error : " + e, Toast.LENGTH_SHORT).show();
}
}
SQLite助手
public void addToFav(String name, String type, String url, String browser, String image) {
SQLiteDatabase favDatabase = getReadableDatabase();
String favAdd =
String.format("INSERT INTO fav(name,url) VALUES('%s','%s');",
name, type, url, browser, image);
favDatabase.execSQL(favAdd);
favDatabase.close();
}
public boolean isFav(String url, String name) {
SQLiteDatabase favDatabase = getReadableDatabase();
String masterQuery = String.format("SELECT * FROM fav WHERE (url= '%s' AND name = '%s')",
url, name);
Cursor cursor = favDatabase.rawQuery(masterQuery, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
favDatabase.close();
return true;
}