Skip to main content

SharedPreferences: History saved but why not Favourite?



I use the following code to save words to History in my dictionary app:







@Override

public void onPause()

{

super.onPause();

saveHistoryToPreferences();

}



public void saveHistoryToPreferences()

{

if (prefs.getBoolean("saveHistory", true) && mWordHistory != null && mWordHistory.size() >= 1)

{

StringBuilder sbHistory = new StringBuilder();

for (String item : mWordHistory)

{

sbHistory.append(item);

sbHistory.append(",");

}

String strHistory = sbHistory.substring(0, sbHistory.length()-1);

SharedPreferences.Editor editor = prefs.edit();

editor.putString("history", strHistory);

editor.commit();

//Log.i(CONTENT_TAG,"history = " + strHistory);

Log.i(CONTENT_TAG,"History saved!");

}

}



public void loadHistoryFromPreferences()

{

if (prefs.getBoolean("saveHistory", true))

{

String strHistory = prefs.getString("history", "");

Log.i(CONTENT_TAG, "History loaded");

if (strHistory != null && !strHistory.equals(""))

{

mWordHistory = new ArrayList<String>(Arrays.asList(strHistory.split(",")));

}

else

{

if (mWordHistory == null)

{

mWordHistory = new ArrayList<String>();

}

else

{

mWordHistory.clear();

}

}

}

else

{

if (mWordHistory == null)

{

mWordHistory = new ArrayList<String>();

}

else

{

mWordHistory.clear();

}

}

}







Everything is working fine with History.





Now I want to adapt this code to save favourite words. Almost every code lines are the same, the only difference is that the adapted code (without onPause() ) is placed under:







btnAddFavourite.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v)

//The code is here...

}







But it is not working and the favourite words are not saved as in the case of History.





Can you guys there help? Thank you very much.


Comments

  1. I am modifying my answer for this StackOverflow link.
    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.

    btnAddFavourite.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v)

    MyUtility.addFavoriteItem(MyActivity.this, "Sports");
    MyUtility.addFavoriteItem(MyActivity.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.

    ReplyDelete

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?

CCNA 1 Final Exam 2011 latest (hot hot hot)

  Hi! I have been posted content of ccna1 final exam (latest and only question.) I will post the answer and insert image on sunday. If you care, please subscribe your email an become a first person have full test content. Subcribe now  Some question  have not content because this question have images content. So that can you wait for me? SUNDAY 1. A user sees the command prompt: Router(config-if)# . What task can be performed at this mode? Reload the device. Perform basic tests. Configure individual interfaces. Configure individual terminal lines. 2. Refer to the exhibit. Host A attempts to establish a TCP/IP session with host C. During this attempt, a frame was captured with the source MAC address 0050.7320.D632 and the destination MAC address 0030.8517.44C4. The packet inside the captured frame has an IP source address 192.168.7.5, and the destination IP address is 192.168.219.24. At which point in the network was this packet captured? leaving host A leaving ATL leaving...