// MODE_PRIVATE means created file can only be accessed by the calling application.
// if the preference file ("file name") does not exist by the given name, file will be created.
SharedPreferences sharedPref = context.getSharedPreferences(
"file name", Context.MODE_PRIVATE);
// Use the following if you need to use only one shared preference file for the activity.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
// Writing to it
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("score", 4);
editor.commit(); // or editor.apply()
/*
* apply() changes the in-memory SharedPreferences object immediately but writes the
* updates to disk asynchronously. Alternatively, you can use commit() to write the
* data to disk synchronously. But because commit() is synchronous, you should avoid
* calling it from your main thread because it could pause your UI rendering.
*/
// Reading from it
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
// 0 is a default value.
int highScore = sharedPref.getInt("score", 0);