好的,我在上面应用了我的建议,测试它并感谢上帝,它完美地工作:]。
这里是任何有兴趣的人的解决方案,但它不是最佳解决方案。
设计与上面略有不同,当点击列表中的一个项目时,将创建一个新的片段,其中包含项目的详细信息和收藏、分享等按钮所以点击功能
public void onClick(View v) {
String fav QuoteIds;
switch (v.getId()) {
case R.id.btn_fav:
if (quote.getFavorite()==0) //Not favorited so add to favorite
{
fav_btn.setBackgroundResource(R.drawable.ic_action_favorited);
//update the object
quote.setFavorite(1);
}
}else //remove from favorite
{
fav_btn.setBackgroundResource(R.drawable.ic_action_favorite);
//update the object
quote.setFavorite(0);
}
//update the database
db.updateQuote (quote);
//Get the id of all favorite quotes to save them in SharedPreferences
favQuoteIds=db.getFavoriteQuotesIds();
db.close();
editor.remove(QUOTES_FAVORITE_IDS); // to keep most recent-
editor.commit();
editor.putString(QUOTES_FAVORITE_IDS, favQuoteIds);//version of user favorite
editor.commit();
在我的自定义 DatabaseHandler 中,我添加了两个函数 [1] getFavoriteQuotesIds,它以“,”分隔的字符串返回最喜欢的引号 ID,以便为更新函数中的 IN 子句做好准备:[2] restoreFavorite()
public String getFavoriteQuotesIds ()
{
String quotes_ids="";
String selectQuery = "SELECT "+KEY_QUOTE_ID+" FROM " + TABLE_QUOTE +" WHERE "+TAG_FAVORITE+"=1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
quotes_ids+=cursor.getString(0)+",";
} while (cursor.moveToNext());
}
//to get rid of last “,”
quotes_ids = quotes_ids.substring(0, quotes_ids.length()-1);
return quotes_ids;
}
现在,当更新数据加载时,引号表将被删除并重新创建,收藏列的默认值为所有引号的 0s
所以我们需要恢复最喜欢的引号,首先,从 sharedpreferences 中获取 ids,然后调用 restoreFavorite 函数来更新数据库
favoriteQuoteIds=sharedPref.getString(QUOTES_FAVORITE_IDS, "");
restoreFavorite(favoriteQuoteIds);
恢复收藏功能
public void restoreFavorite(String ids) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TAG_FAVORITE, 1);
// updating row
db.update(TABLE_QUOTE, values, KEY_QUOTE_ID + " IN(" + ids + ")",null);
}
剩下的是任何 qoute 的初始收藏按钮状态所以,在 OnViewCreated 中检查它
if(quote.getFavorite()==1)
fav_btn.setBackgroundResource(R.drawable.ic_action_favorited);
else
fav_btn.setBackgroundResource(R.drawable.ic_action_favorite);