Store Data – SharedPreferences – Android

Home / Android / Store Data – SharedPreferences – Android

When it comes to store data like

  • username for a user specific application, or
  • checking how many times the application is opened.

It is not a good choice to manage a database. As mentioned in previous blog posts, Android SQLite Database – Part 1, and Android SQLite Database – Part 2, it will be time consuming. In conjunction to that, it is not going to fulfil why database is for and database transactions are costly for such one time transaction. So, it is good if you choose to save data, like in above example, in SharedPreferences.

SharedPreferences are used as XML based database in Android applications. All information are stored as pair. It is stored in private location, allocated to each application, on SD Card. Its content can be viewed only in two cases:

  1. If you are using emulator, and
  2. If your device is rooted.

It’s location is /data/data/<your_app_package_name>/shared_prefs. Name of SharedPreferences depends on how it is created.

There are two ways to create SharedPreferences:

  1. PreferenceManager.getDefaultSharedPreferences(Context context), and
  2. getSharedPreferences(String name, int mode)

If created using 1st method, then the name of SharedPreferences will be <package_name>_preferences.xml. And if created with 2nd method, the name will be same as parameter name.

There is no limitation on creating SharedPreferences by method 2. All the information stored inside it will be accessed by only that application. No other application have permission to access SharedPreferences.

In Storing data in SharedPreferences – Android we discuss about storing and removing data from SharedPreferences.