How to use SharedPreferences to save more than one values?

前端 未结 6 1576
慢半拍i
慢半拍i 2020-11-29 08:03

I am developing a dictionary app. In my app, I assume that user wants to save favourite words. I have decided to use SharedPreferences to save these values

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 08:30

    Honeycomb added the putStringSet method, so you could use that if you don't have to support anything less than Honeycomb:

    @Override
    public void onClick(View v) {
        SharedPreferences faves = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        {
            Set faveSet = faves.getStringSet("favourite");
            faveSet.add(mSelectedDB + "::" + mCurrentWordId + "::" + mCurrentWord + ",");
            SharedPreferences.Editor editor = faves.edit();
            editor.putStringSet("favourite", faveSet);
            editor.commit();
        }
        Log.i(CONTENT_TAG,"Favourite saved!");
    
        Toast toast = Toast.makeText(ContentView.this, R.string.messageWordAddedToFarvourite, Toast.LENGTH_SHORT);
        toast.show();
    }
    

    If you need support for pre-Honeycomb devices, you will have to come up with your own scheme.

    One possibility is to store the words as comma-separated values in one preference.

    Another is to generate a new key for each new word, "favourite1", "favourite2", "favourite3" and have another preference you use to store the number of words.

提交回复
热议问题