Saturday, 12 September 2015

Shared Preference (for storage)

This is a simple api that allows the user to save the key value pairs.

For a simple example
we will create a global edittext

get reference to it in the oncreate method

then we create an instance of shared preferences

SharedPreferences setting=getSharedPreferences("MYPREFS",0);
MYPREFS is the file and if it doesnt exist , it will go and create that

Now what we want t odo it read it and put whatever value it has in the edit text

et.setText(setting.getString("tvalue","this is default value"),);

now we try to extract a string out of it , (tvalue is just any name, a key name, its like a map and the key value thing that we generally use) , and if any value 
doesn't exist it just tries to read the second parameter which makes it the default values.


Now ,we want to save whatever we have written in that edittext before we exit
so we override onstop method

@Overrideprotected void onStop() {
    super.onStop();
    SharedPreferences setting= getSharedPreferences("MYPREFS",0);// again create shared preference
   to do changes to this shared preferences we need call an editor
    SharedPreferences.Editor editor= setting.edit();
    editor.putString("tvalue",et.getText().toString());
// put value that is there in the edit text and the keyvalue is Tvalue
     editor.commit();
// and the last this is to commit the changes that we have done
    



}

No comments:

Post a Comment