Shared preferences

This is one of the way to store data permanantly. This is used for storing a short list of data or one-off variables which are changed rarely

For larger data, we ll be using databases (later)

Storing Strings

SharedPreferences sharedPreferences = this.getSharedPreferences(getPackageName(),Context.MODE_PRIVATE);

//Entering data when run for first time, comment otherwise
sharedPreferences.edit().putString("username","aravind").apply();

//retrieving data. Provide the key and a default value
String username = sharedPreferences.getString("username","");

Log.i("username",username);

Note : Difference between sharedPreference.apply() and sharedPreference.commit()

apply() was added in 2.3, it commits without returning a boolean indicating success or failure.

commit() returns true if the save works, false otherwise.

Storing Arrays - using ObjectSerializer

For arrays, we ll have to serialize them before storing them.

To serialize, we add a new class ObjectSerializer from apache to our project.

File -> new class.

New class will be stored in the same folder as MainActivity.java

//saving arrays in shared preferences

ArrayList<String> friends = new ArrayList<>();
friends.add("AA");
friends.add("BB");

try {
    //arrays have to be serialized to strings. We have added a class ObjectSerializer to the project
    sharedPreferences.edit().putString("friends", ObjectSerializer.serialize(friends)).apply();
} catch (IOException e) {
    e.printStackTrace();
}

ArrayList<String> newFriends =new ArrayList<>();


try {
    //get the string and deserialize. provide default string value
    newFriends = (ArrayList<String>)ObjectSerializer.deserialize(
            sharedPreferences.getString("friends",ObjectSerializer.serialize(new ArrayList<>())));
} catch (IOException e) {
    e.printStackTrace();
}

Log.i("Friends",newFriends.toString());

Storing arrays : using HashSet

HashSet are like arrays but with no items repeated

This method DOES NOT PRESERVE ORDER of retrieval. So if we need two arrays synched, this wont work (Memorable places project). But this is good enough for Notes project

//get array
HashSet<String> set = (HashSet<String>)sharedPreferences.getStringSet("notes",null);
if(set == null)
    notes = new ArrayList<>();
else
    notes = new ArrayList<>(set);

//put array
HashSet<String> set = new HashSet<>(notes);
sharedPreferences.edit().putStringSet("notes",set).apply();

Clearing preferences

sharedPreferences.edit().clear().apply();

Limitation:

Not all java objects are serializable. We may have to store the params separately and recreate those objects on every run

Example in MemorablePlaces project