Kalpana Devkota
Kalpana Devkota

Reputation: 63

How to store string array using SharedPreference?

I want to save two string values on checking toggle button and retrieve it from another Fragment. This is what I did to the button OnClickListener but it isn't working:

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

This is my SharedPreference class

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

Upvotes: 0

Views: 1566

Answers (1)

Juan Manuel Ojeda
Juan Manuel Ojeda

Reputation: 19

let's solve this ^^. You can save multiple favorites in a single preference by adding numerous favorites in a single string, each favorite item separated by comma. Then you can use convertStringToArray method to convert it into String Array. Here is the full source code. Use MyUtility Methods to save multiple favorite items.

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

get String array of all favorites saved

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

Save these methods in separate Utility class

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

}

If you have to add extra favorites. Then get favorite string from SharedPreference and append comma+favorite item and save it back into SharedPreference. * You can use any other string for separator instead of comma.

Upvotes: 2

Related Questions