- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个远程数据库,其中包含在新版本数据可用时定期加载到 Android 应用程序的数据 - 即添加了新数据或编辑了现有数据。即使数据已重新加载,我也需要保留用户对数据的偏好。
例如数据是语录的集合,无需用户注册,用户可以收藏自己喜欢的任何语录。为了加快应用程序的速度,数据存储在 sqlite 数据库中。
现在当有新版本可用时,数据将被重新加载,那么标记已经收藏的引述(如收藏的推文)的最佳方式是什么,下图显示了这个想法
我想在本地数据库中添加一个额外的二进制列,用于收藏/不喜欢。另外在设备中存储收藏的 qoutes 的 ids (SharedPreferences)当加载更新的数据时,将其 id 存储在设备中的 qoutes 的最喜欢的列更新为 1,对于其余部分,最喜欢的列的默认值为 0。这应该可行,但我认为可能有更好的解决方案。任何建议,谢谢!
最佳答案
好的,我应用了我上面的建议,测试它并感谢上帝,它完美地工作:]。
这里是适合任何感兴趣的人的解决方案,但它不是最佳解决方案。
设计与上面略有不同,当单击列表中的项目时,将创建一个新 fragment ,其中包含项目的详细信息以及收藏、分享等按钮所以点击功能
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;
}
现在当加载更新数据时,报价表将被删除并重新创建,所有报价的收藏夹列的默认值为 0
所以我们需要恢复最喜欢的报价,首先,从 sharedpreferences 中获取 id,然后调用 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);
关于Android应用如何存储用户喜爱的数据来个性化动态数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22447368/
我是一名优秀的程序员,十分优秀!