0
我想在检查切换按钮时保存两个字符串值,并从另一个Fragment
检索它。这是我所做的按钮OnClickListener
,但它不工作:如何使用SharedPreference存储字符串数组?
holder.favButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton favButton, boolean isChecked){
if (isChecked)
favButton.setBackgroundDrawable(ContextCompat.getDrawable(favButton.getContext(),R.mipmap.ic_launcher));
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("PRODUCT_APP", "Product_Favorite").commit();
else
favButton.setBackgroundDrawable(ContextCompat.getDrawable(favButton.getContext(), R.mipmap.ic_cart));
}
});
这是我SharedPreference
类
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<CardItemModel> favorites) {
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, CardItemModel product) {
List<CardItemModel> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<CardItemModel>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, CardItemModel product) {
ArrayList<CardItemModel> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<CardItemModel> getFavorites(Context context) {
SharedPreferences settings;
List<CardItemModel> favorites;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
CardItemModel[] favoriteItems = gson.fromJson(jsonFavorites,
CardItemModel[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<CardItemModel>(favorites);
} else
return null;
return (ArrayList<CardItemModel>) favorites;
}
}
此链接可能很有用:http://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences – Koorosh
你的'setOnCheckedChangeListener'不应该工作。没有相应的最后一部分。请先修复您的代码,然后再次发布代码。它应该给你一个编译错误。 –