Search code examples
androidstorageinternal

Save more than one string to the same internal storage


I need to do something like this:

In first Activity, I save the first string to the internal storage and in second Activity I save the second string to the same internal storage.

I have problem, when I try to save the second string, internal storage always keeps only the last string and previous disappears.

Is there any solution?


Solution

  • Internal storage is based on key-value system. So it is normal, that for 1 key, there is only 1 value available. You can append the new value somehow like this:

    private static final String SETTINGS_NAME = "my_settings.cfg";
    private static final String DELIM = ";";
    
    public void settingsAppendValue(Context context, String key, String value)
    {
        SharedPreferences settings = context.getSharedPreferences(SETTINGS_NAME, Context.MODE_PRIVATE);
        String actualValue = settings.getString(key, "");
    
        Editor editor = settings.edit();
        actualValue += (actualValue.length() > 0 ? DELIM : "") + value;
        editor.putString(key, actualValue);
        editor.commit();        
    }
    
    public String[] settingsGetValues(Context context, String key)
    {
        SharedPreferences settings = context.getSharedPreferences(SETTINGS_NAME, Context.MODE_PRIVATE);
        return settings.getString(key, "").split(DELIM);        
    }