Ok, I applied my suggestion above, test it and thanks God,it flawlessly works :].
Here the solution for anyone who is interested, it is not the optimal one though.
The design is slightly differ from above, when an item in the list been clicked, a new fragment will be created contain details of item and favorite, share, etc buttons So on click function
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();
Inside My custom DatabaseHandler I add two functions [1] getFavoriteQuotesIds which returns favorited quotes ids as string seperated by "," to to be ready for IN clause inside update function: [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;
}
Now when update data loaded, the table of quotes will be dropped and recreated, the default value for favorite column is 0s for all quotes
So we need to restore favorite quotes, first, get the ids from sharedpreferences, Second call restoreFavorite function which will update the database
favoriteQuoteIds=sharedPref.getString(QUOTES_FAVORITE_IDS, "");
restoreFavorite(favoriteQuoteIds);
restoreFavorite function
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);
}
What remain is the initial favorite button state for any qoute So, check for it inside OnViewCreated
if(quote.getFavorite()==1)
fav_btn.setBackgroundResource(R.drawable.ic_action_favorited);
else
fav_btn.setBackgroundResource(R.drawable.ic_action_favorite);