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
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 valuedoesn'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 exitso we override onstop method@Overrideprotected void onStop() { super.onStop(); SharedPreferences setting= getSharedPreferences("MYPREFS",0);// again create shared preferenceto do changes to this shared preferences we need call an editorSharedPreferences.Editor editor= setting.edit();editor.putString("tvalue",et.getText().toString());// put value that is there in the edit text and the keyvalue is Tvalueeditor.commit();// and the last this is to commit the changes that we have done}
No comments:
Post a Comment