To use it, first create get a reference to the SharedPreferences with
SharedPreferences preferences = Context.getPreferences(int mode);
If you are calling from your main activity you can just leave out Context, otherwise you need to provide it. mode specifies whether other applications can access your SharedPreferences. 0 means they can't, 1 means they can read them and 2 means they can read and write to them.
If you would like to have more than one SharedPreferences file you can use
Context.getSharedPreferences(String name, int mode);
instead, however this isn't really necessary as you can store as many objects as you want in one SharedPreferences file.
Now that you have the reference, to store data in the file you will need to get a SharedPreferences Editor, and then use that to make the changes
SharedPreferences.Editor editor = preferences.edit();
As you can see, we first get a reference to the editor, and then use that to put in an int which we called "exampleName" and that has a value of exampleValue. Finally we called commit which actually saves the changes.
To later read values from SharedPreferences is even easier, just use:
exampleInt = preferences.getInt("exampleName", int defaultValue);
exampleString = preferences.getString("exampleStringName", String defaultValue);
In this case, if an object with the name you specified does not exist in the SharedPreferences, then the default value will be returned instead, useful for telling if someone is playing your game for the first time.
That's pretty much all there is to it. You can remove certain values if you want by using Editor.remove(String name) and then calling Editor.commit(). In future posts I'll be looking at other ways of storing data, but for simple things I would always use SharedPreferences.
Questions regarding the post or ideas for an upcoming article? Go ahead and leave a comment