Search code examples
javaandroidsharedpreferencespersistent

Persistent data to save name and website from input user


I have two edit text for the name and the url. After pressing "save" button I want to save this informations.

So I decided to use SharedPreferences to store it and it's ok.

SharedPreferences addActivityPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = addActivityPrefs.edit(); editor.putString("name", name.getText().toString()).commit(); editor.putString("url", url.getText().toString()).commit();

But my problem is when I want to store others values it overwrites my previous values and I want to keep all of them.

this is my xml file :

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
     <string name="url">http://Google.co.uk</string>
     <string name="name">BBC world news feed</string>
</map>

And my goal is to save many pairs of name-url like http://www.google.co.uk GOOGLE

<map>
    <string name="url">http://www.yahoo.co.uk</string>
    <string name="name">YAhoo</string>
</map>

and so on and so forth.


Solution

  • You could store the array as a string and save that, or you can just create a new key for each item, so have

    1. location1
    2. location2
    3. location3

    To do the second approach you can look at this question:

    Android store array in preferences

    I would also have a key with the number of saved items, so you can load that key, increment, save, then use the new counter as the name of the new key, so location + cntr