Shared preferences stores data as key/value pairs.
To put the key/value pair into shared preferences you can use the .commit() or .apply() command.
apply()
This saves your data into memory immediately and saves the data to disk on a separate thread. So there is no chance of blocking the main thread (your app won’t hang).
It is the preferred technique but has only been available since Gingerbread (API 9, Android 2.3).
commit()
Calling this will save the data to the file however, the process is carried out in the thread that called it, stopping everything else until the save is complete. It returns true on successful completion, false on failure.
Use commit() if you need confirmation of the success of saving your data or if you are developing for pre-Gingerbread devices. commit() has been available since API 1
The following code will setup shared_prefs file and store different values.
public static final String MyPREFERENCES = "MyPrefs"; //This will be the name of the shared preferences file
public static final String Name = "nameKey";
SharedPreferences sharedpreferences;
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, "string");
editor.putBoolean(Name2, false);
editor.putInt(Name3, 23424);
editor.apply();
A good idea is to put the code for shared preferences into its own class and declare static methods. Here is an example for putting a boolean value into shared preferences:
import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; public class PreferencesMgr { private static SharedPreferences sSharedPreferences; public static final String MyPREFERENCES = "MyPrefs";//This will be the name of shared preferences file. public static void setBoolean(Context context, String key, boolean data ){ Log.i("PrefMgr setBoolean", "key: " + key + ", data: " + data); sSharedPreferences = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sSharedPreferences.edit(); editor.putBoolean(key, data); editor.apply(); } public static Boolean getBoolean(Context context, String key){ sSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); return sSharedPreferences.getBoolean(key, false); } }
You then set the boolean value with:
PreferencesMgr.setBoolean(this,KEY,true);
and you retrieve it using:
boolean myBoolean = PreferencesMgr.getBoolean(context, KEY);
You can view the shared_prefs file using a command prompt after the file has been created.