Question

My application is basically a quiz that presents people with world flags. I want to add a save function that adds the current flag to a separate list. Right now, this is what I do when they click the "save" button:

saveListGC.add(playList.get(1));

(playList.get(1) is the current flag). The problem is, I have to re-define the saveListGC every time the script starts, and that empties the contents:

public static ArrayList<String> saveListGC = new ArrayList<String>();

So what I'm wondering is how can I save this data, and re-load it later? I've seen things about using SharedPrefernces, but I don't really understand it. If someone could please explain it as easily as possible, I would really appreciate it. Thank you!

Was it helpful?

Solution

This a simple example of how you can use SharedPreferences:

    //intiat your shared pref
    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
    Editor editor = pref.edit();

    //store data to pref
    editor.putString("myString", "value 1");
    editor.commit();

    //retrieve data from pref
    String myString = pref.getString("myString", null);

But the real problem here is that SharedPreferences can not store an Object of type List (ArrayList), but you can store an Object of type Set (like Hashset) using this method

Set<String> mySet = new HashSet<String>(); 
mySet.add("value1");
mySet.add("value2");
mySet.add("value3");

editor.putStringSet("MySet", mySet);

So to answer your second question, this what i propose for you to do:

//This is your List
ArrayList<String> saveListGC = new ArrayList<String>();

//Convert your List to a Set
Set<String> saveSetGC = new HashSet<String>(saveListGC);

//Now Store Data to the SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
Editor editor = pref.edit();
editor.putStringSet("MySet", saveSetGC);
editor.commit();

//After that in another place or in another Activity , Or every where in your app you can Retreive your List back
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Set<String> mySetBack = pref.getStringSet("MySet", null);
//Convert Your Set to List again
ArrayList<String> myListBack = new ArrayList<String>(mySetBack);

//Here you can se the List as you like...............
Log.i("MyTag", myListBack.get(0));
Log.i("MyTag", myListBack.get(1));

Good Luck :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top