Append more values to Shared Preferences rather than overwriting the existing values

前端 未结 3 1905
孤独总比滥情好
孤独总比滥情好 2021-01-20 23:27

In my app, I need the values to be saved in to Sharedpreferences file RKs_Data without overwriting the existing data. Every time, I click \'Yes\' in my app, I require all the va

3条回答
  •  天命终不由人
    2021-01-21 00:11

    you could CSV format your shared preference data. For example, Get CSV string from shared preference and add it to a list. Append to your list then put it back into your sharedpreferance. Code example

    // init List of strings somewhere before

    List  listOfFavoritePhrases = new ArrayList();
    

    // append data into list

    listOfFavoritePhrases.add("Brian|99999299999");
    listOfFavoritePhrases.add("Monet|00010000000");
    

    // Put list of strings after you have made changes back, in CSV format

    SharedPreferences prefs = getSharedPreferences("PACKAGE", Context.MODE_PRIVATE);
                SharedPreferences.Editor   editor = prefs.edit();
                editor.putString("phrases",TextUtils.join(",", listOfFavoritePhrases));
                editor.commit();
    

    // get data

         SharedPreferences prefs = getSharedPreferences("PACKAGE", Context.MODE_PRIVATE);
        String serialized = prefs.getString("phrases", "Brian");
         listOfFavoritePhrases = new ArrayList(Arrays.asList(TextUtils.split(serialized, ",")));
    

    and then

    String CurrentString = listOfFavoritePhrases.get(0); // first element
    String[] separated = CurrentString.split("|");
    Toast.makeText(this, separated[0], Toast.LENGTH_LONG).show(); // brian
    Toast.makeText(this, separated[1], Toast.LENGTH_LONG).show(); // 99999299999
    

    Hope this Helps.

提交回复
热议问题