【问题标题】:How to store string array using SharedPreference?如何使用 SharedPreference 存储字符串数组?
【发布时间】:2017-05-21 02:54:13
【问题描述】:

我想在检查切换按钮时保存两个字符串值并从另一个Fragment 检索它。这是我对按钮 OnClickListener 所做的,但它不起作用:

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;
    }
}

【问题讨论】:

  • 这个链接很有用:stackoverflow.com/questions/7057845/…
  • 您的setOnCheckedChangeListener 不应该工作。没有 if 对应最后一个 else 部分。请先修复您的代码,然后再次发布代码。它应该会给你一个编译错误。

标签: android android-fragments android-recyclerview sharedpreferences


【解决方案1】:

让我们解决这个问题^^。 您可以在单个首选项中保存多个收藏夹,方法是在单个字符串中添加多个收藏夹,每个收藏夹项目以逗号分隔。然后您可以使用convertStringToArray 方法将其转换为字符串数组。这是完整的源代码。 使用 MyUtility 方法保存多个收藏项。

  MyUtility.addFavoriteItem(this, "Sports");
        MyUtility.addFavoriteItem(this, "Entertainment");

获取保存的所有收藏夹的字符串数组

String[] favorites = MyUtility.getFavoriteList(this);// returns {"Sports","Entertainment"};

将这些方法保存在单独的实用程序类中

public abstract class MyUtility {

public static boolean addFavoriteItem(Activity activity,String favoriteItem){
    //Get previous favorite items
    String favoriteList = getStringFromPreferences(activity,null,"favorites");
    // Append new Favorite item
    if(favoriteList!=null){
        favoriteList = favoriteList+","+favoriteItem;
    }else{
        favoriteList = favoriteItem;
    }
    // Save in Shared Preferences
    return putStringInPreferences(activity,favoriteList,"favorites");
}
public static String[] getFavoriteList(Activity activity){
    String favoriteList = getStringFromPreferences(activity,null,"favorites");
    return convertStringToArray(favoriteList);
}
private static boolean putStringInPreferences(Activity activity,String nick,String key){
    SharedPreferences sharedPreferences = activity.getPreferences(Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, nick);
    editor.commit();                        
    return true;        
}
private static String getStringFromPreferences(Activity activity,String defaultValue,String key){
    SharedPreferences sharedPreferences = activity.getPreferences(Activity.MODE_PRIVATE);
    String temp = sharedPreferences.getString(key, defaultValue);
    return temp;        
}

private static String[] convertStringToArray(String str){
    String[] arr = str.split(",");
    return arr;
}

}

如果您必须添加额外的收藏夹。然后从SharedPreference 获取最喜欢的字符串并附加逗号+最喜欢的项目并将其保存回SharedPreference。 * 您可以使用任何其他字符串作为分隔符,而不是逗号。

【讨论】:

    猜你喜欢
    • 2013-11-14
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    相关资源
    最近更新 更多