Tuesday, October 25, 2022

Android - Shared Preferences

 

Android - Shared Preferences


Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key,value pair.

In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

The first parameter is the key and the second parameter is the MODE. Apart from private there are other modes available that are listed below −


Sr.NoMode & description
1

MODE_APPEND

This will append the new preferences with the already existing preferences

2

MODE_ENABLE_WRITE_AHEAD_LOGGING

Database open flag. When it is set , it would enable write ahead logging by default

3

MODE_MULTI_PROCESS

This method will check for modification of preferences even if the sharedpreference instance has already been loaded

4

MODE_PRIVATE

By setting this mode, the file can only be accessed using calling application

5

MODE_WORLD_READABLE

This mode allow other application to read the preferences

6

MODE_WORLD_WRITEABLE

This mode allow other application to write the preferences


You can save something in the sharedpreferences by using SharedPreferences.Editor class. You will call the edit method of SharedPreference instance and will receive it in an editor object. Its syntax is −

Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();



Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
        getString
(R.string.preference_file_key), Context.MODE_PRIVATE);

or 

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);


SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor
.putInt(getString(R.string.saved_high_score_key), newHighScore);
editor
.apply();


SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key);
int highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue);

No comments:

Post a Comment