Using SharedPreferences


Hi , as we all know when developing applications we need some to remain through out the app or need data which need to initalise when application is run for first time and changes through time depending upon the situation.

If you are a java programmer you might probably be using properties file which store value in key-pair values for easy read write of data. For android you can use SharedPreference which allows to read write data values in key value pair.
You can create a new shared preference file or access an existing one by calling one of two methods:

1. getSharedPreferences() — Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any Context in your app.

Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
        getString(resource id), Context.MODE_PRIVATE);
Note : getString method can be accessed from the Context object , it take resource as parameter

2. getPreferences() — Use this from an Activity if you need to use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, you don't need to supply a name.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

3. To write to a shared preferences file, create a SharedPreferences.Editor by calling edit() on your SharedPreferences. Pass the keys and values you want to write with methods such as putInt() and putString(). Then call commit() to save the changes.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(“YourKEY”, “MY VALUE”);

4. To get values from a shared preferences file, call methods such as getInt() and getString(), providing the key for the value you want, and optionally a default value to return if the key isn't present.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
long highScore = sharedPref.getInt(getString(“MyKEY”, “Default Value if no value is found”);

5. To remove value from the shared preference SharedPreferences.Editor ,remove(String) can be used.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();

Post a Comment

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !