How to use SharedPreferences to save more than one values?

前端 未结 6 1569
慢半拍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:31

    Every time you click the button you save the favorite word with the already present key: favorite and you override it. To save more than one word you have to save the words with different keys. So every time you save a favorite word you could do:

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

提交回复
热议问题