Android Shared Preferences API tutorial

If you want to store information/data at the application level then it can be achieved using Shared Preferences. The data that you store using Shared Preferences will persist even after relaunch and reboot.

Note: If the user goes to Setting->Application setting->Application and Clears the data (Clear data option) for you app then all the data stored will be deleted.

How to use SharePreferences

Data is scored as Key-Value Pairs using SharedPreferences APIs.

There are two ways (methods) in which you can use SharedPreferences.

1. getPreferences()

This method should be used if your application needs only one shared preference file for your activity. This uses a default shared preference file and hence there is no need to specify the file name for it.

Example :

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

2. getSharedPreferences()

You need to have the application Context object in order to access/call shared preferences,

Example :
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
"com.code2care.sharedPreferences.pref_file_key", Context.MODE_PRIVATE);

You may use this method if you need more than one shared preference file. getSharedPreferences() signature has two parameters 1st one specifies the shared preference file names and the second parameter specifies how the file would be accessed. Note that the shared preference file name should uniquely identify your app and must be specified as "com.companyname.appname.pref_file_name"

SharePreferences File Access Modes

You can use the following modes to create or access SharePreferences file,

1. MODE_PRIVATE

This is a default file creation mode. When this mode has used the file created can be accessed only by the application that creates it. It has a constant value 0.

Definition : public static final int MODE_PRIVATE = 0

2. MODE_APPEND

This file creation mode is used when the file already exists and data is to be written to the existing file at the end of the file.

3. MODE_ENABLE_WRITE_AHEAD_LOGGING

This is a database open flag, when it is set the database is opened with write-ahead logging enabled mode.

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!