user3203324
user3203324

Reputation: 31

Use sharedPreferences to add values to a string

My goal is to save a value to a string, and then store the string to sharedPreferences. Moreover, every time the app generates a new value, I would like to add this string to the string array, which would increase the length of the string array by 1 every time the app is used. I have spent 200+ hours trying to make this work, but I still can't get it to work properly. This is what I have so far:

public class MainActivity extends Activity {

Set set = new HashSet();
set.add(EnterText.mynumber);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences sharedPreferences = getSharedPreferences(days,Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putStringSet("strings", set);
        Boolean flag = editor.commit();

        SharedPreferences prefs = getSharedPreferences("MyPrefs",Activity.MODE_PRIVATE);
        Set set=new HashSet();
        set=prefs.getStringSet("strings", null);

    }

}

If anyone knows the right method to do this, or how I can fix this code to make it work, I would greatly appreciate it.

Thanks for your help

Upvotes: 0

Views: 50

Answers (1)

Mika
Mika

Reputation: 5845

You should use putStringSet instead of putString.

Basically you need to create a set with all of your strings.

Set set =new HashSet();
set.add("String 1");
set.add("String 2");
set.add("String 3");

Then you can write:

SharedPreferences prefs = getSharedPreferences("MyPrefs",
        Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet("strings", set);
Boolean flag = editor.commit();

To get it back the next time you run the app you can do:

SharedPreferences prefs = getSharedPreferences("MyPrefs",
        Activity.MODE_PRIVATE);
Set set=new HashSet();
set=prefs.getStringSet("strings", null);

Upvotes: 2

Related Questions