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

前端 未结 3 1869
孤独总比滥情好
孤独总比滥情好 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:07

    Follow these steps:

    Extract the value stored in SharedPreferences

    String value = prefs.getString(<Key>, <DefaultValue>);
    

    Append to the extracted value

    String appendedValue = append(value, newValue);
    

    Write the result back to SharedPreferences

    editor.putString(<Key>, appendedValue).commit();
    
    0 讨论(0)
  • 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<String>  listOfFavoritePhrases = new ArrayList<String>();
    

    // 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<String>(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.

    0 讨论(0)
  • 2021-01-21 00:23

    Finally my code looks like this: Sharing the final code as it can be useful to others who are newbies like me :)


    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.rks_contactslist_main);
            ListView listview = getListView();
    
            sp = getSharedPreferences("PACKAGE", Context.MODE_PRIVATE);
            String str = sp.getString("FAV_CONTACS",
                    "NO fav contacts are saved as of now");
    ---------
    
    protected void onListItemClick(ListView listview, View view, int position,
                long id) {
            // TODO Auto-generated method stub
            super.onListItemClick(listview, view, position, id);
            ContactBean bean = (ContactBean) listview.getItemAtPosition(position);
    
            showCallDialog(bean.getName(), bean.getPhoneNo());
        }
    
    
    ---------
    
        public void onClick(DialogInterface dialog, int which) {
                    Fav_Contacts_file = getFilesDir();
                        if (count <5) {
                            SharedPreferences.Editor editor = sp.edit();
    
                            String new_contact = name + " " + phoneNo;
    
    
                            String existing_contact = sp.getString("CONTACTS", "");
                            /*String existing_phone = sp.getString("phoneNo", "");
                            String existing_contact = existing_name + " " +existing_phone ;*/
    
    
                            String latestfavContacts = append(existing_contact, new_contact);
    
    
                            editor.putString("CONTACTS", latestfavContacts);
                            editor.commit();
                            count++;
                            Toast.makeText(
                                    getApplicationContext(),
                                    "The data saved successfully to ........ : "
                                            + Fav_Contacts_file + "/PACKAGE",
                                    Toast.LENGTH_SHORT).show();
                            Toast.makeText(
                                    getApplicationContext(),
                                    "Name : " + name + " and Phone : "
                                            + phoneNo, Toast.LENGTH_SHORT)
                                    .show();
                        }
                        else {
                            Toast.makeText(
                                    getApplicationContext(),
                                    "More than 5 Fav Contacts are NOT allowed",                                     
                                    Toast.LENGTH_SHORT).show();
                        }
    
                    }
                });
                alert.show();
            }
    
            protected String append(String existing_contact, String new_contact) {
                String latestfavContacts = existing_contact + " | "+ new_contact ;
                return latestfavContacts;
            }
    

    and the data stored in SharedPreference file 'PACAKAGE' looks like this:

    <?xml version="1.0" encoding="UTF-8" standalone="true"?>
    -<map>
    <string name="CONTACTS"> | Alen 1 231-231-231 | Alex Zun 1 234-321-231 | Dr. S.K. Taher Ali 040-7265587 | Gazer 1 312-345-452 | Helen (432) 341-1343</string>
    </map>
    

    I'm yet to work on the formatting and present it to the UI friendly mode as per my application needs.

    0 讨论(0)
提交回复
热议问题