Home Tutorials Training Consulting Products Books Company Donate Contact us

NOW Hiring

Quick links


File based persistence in Android. This tutorial describes how to save key-value pairs using the preference API in Android. It also explains how to read and write files in Android.

1. File based persistence

1.1. Methods of local data persistence

Android allows to persists application data via the file system. For each application the Android system creates a data/data/[application package] directory.

Android supports the following ways of storing data in the local file system:

  • Files - You can create and update files

  • Preferences - Android allows you to save and retrieve persistent key-value pairs of primitive data type.

  • SQLite database - instances of SQLite databases are also stored on the local file system.

Files are saved in the files folder and application settings are saved as XML files in the shared_prefs folder.

If your application creates an SQLite database this database is saved in the main application directory under the databases folder.

The following screenshot shows a file system which contains file, cache files and preferences.

Screenshot of the file system with a few files

Only the application can write into its application directory. It can create additional sub-directories in this application directory. For these sub-directories, the application can grant read or write permissions for other applications.

1.2. Internal vs. external storage

Android has internal storage and external storage. External storage is not private and may not always be availale. If, for example, the Android device is connected with a computer, the computer may mount the external system via USB and that makes this external storage not avaiable for Android applications.

1.3. Application on external storage

As of Android 8 SDK level it is possible to define that the application can or should be placed on external storage. For this set the android:installLocation to preferExternal or auto.

In this case certain application components may be stored on an encrypted external mount point. Database and other private data will still be stored in the internal storage system.

2. Preferences

2.1. Storing key-value pairs

Android supports the usage of the SharedPreferences class for persisting key-value pairs (preferences)of primitive data types in the Android file system.

The definition of these preferences can be done via an XML resource.

The PreferenceManager class provides methods to get access to preferences stored in a certain file. The following code shows how to access preferences from a certain file

# getting preferences from a specified file
SharedPreferences settings = getSharedPreferences("Test", Context.MODE_PRIVATE);

Preferences should be created private for the application. They can be accessed via all application components. Sharing data with other application with world readable or writable preference file is rarely used, as the external component would need to know the exact filename and location of the file.

The default preferences are available from any component via the PreferenceManager.getDefaultSharedPreferences(this) method call. Preference value are accessed via the key and the instance of the SharedPreferences class, as demonstrated in the following listing.

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity();
String url = settings.getString("url", "n/a");

To create or change preferences you have to call the edit() method on the SharedPreferences object. Once you have changed the value you have to call the apply() method to apply your asynchronously to the file system. The usage of the commit() method is discouraged, as it write the changes synchronously to the file system.

Editor edit = preferences.edit();
edit.putString("username", "new_value_for_user");

2.2. Preference Listener

You can listen to changes in the preferences via the registerOnSharedPreferenceChangeListener() method on SharedPreferences.

SharedPreferences prefs =

// Instance field for listener
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
  public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    // Your Implementation


One watch out is that SharedPreferences keeps listeners in a WeakHashMap hence listener may be recycled if your code does not hold a reference to it.

3. Tutorial: Prerequirements

The following tutorial is based on the "de.vogella.android.socialapp" example from http://www.vogella.com/tutorials/Android/article.html#menu_tutorial - Android action bar tutorial.

4. Exercise: Prerequisites

The following exercise assumes that you have created an Android project called com.example.android.rssfeed with one entry called Settings in the action bar.

5. Exercise: Preference setting for the RSSfeed

In this exercise you allow the user to enter his preferred URL for an RSS feed via another activity. This activity uses a preference xml file to define the user interface.

5.1. Create preference file

Create an Android XML resource called mypreferences.xml in the xml folder. Add entries to this file similar to the following listing.

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

        android:title="Rss feed URL"
    <CheckBoxPreference android:title="Aktiv" android:key="active"/>


5.2. Create settings activity

Create the class SettingsActivity. It should extends PreferenceActivity. This activity loads the preference file and allows the user to change the values.

package com.example.android.rssreader;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class SettingsActivity extends PreferenceActivity {
        public void onCreate(Bundle savedInstanceState) {

Remember that you need to register the activity in the Android manifest.

5.3. Connect your settings activity

Ensure that you open the preference activity via the onOptionsItemSelected() method. The relevant code is demonstrated in the following listing.

public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        // more code...
        case R.id.preferences:
                // Launch settings activity
                Intent i = new Intent(this, SettingsActivity.class);
                // more code...
        // more code...

5.4. Use the preference value to load the RSS feed

The following code snippet demonstrates how you can access the preference value in a method.

// if you use this in a service or activity you can use this
// if you use this in a fragment use getActivity() or getContent() as parameter
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String url = settings.getString("url", "http://www.vogella.com/article.rss");

5.5. Validating

Run your application. Select from your action bar the Settings action. You should be able to enter a URL. If you press the back button and press the refresh button, ensure that the value of the url preference is used in your activity.

5.6. Optional: Show the current value in the settings

The following code snippet demonstrates how to show the current value in the preference screen.

package com.example.android.rssreader;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;

public class SettingsActivity extends PreferenceActivity implements
                OnSharedPreferenceChangeListener {

        public void onCreate(Bundle savedInstanceState) {

                // show the current value in the settings screen
                for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {

        protected void onResume() {

        protected void onPause() {

        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                        String key) {

        private void initSummary(Preference p) {
                if (p instanceof PreferenceCategory) {
                        PreferenceCategory cat = (PreferenceCategory) p;
                        for (int i = 0; i < cat.getPreferenceCount(); i++) {
                } else {

        private void updatePreferences(Preference p) {
                if (p instanceof EditTextPreference) {
                        EditTextPreference editTextPref = (EditTextPreference) p;
Showing the current value in the preferences

6. Android File API

6.1. Using the file API

Access to the file system is performed via the standard java.io classes. Android provides also helper classes for creating and accessing new files and directories. For example the getDir(String, int) method would create or access a directory. The openFileInput(String s) method would open a file for input and openFileOutput(String s, Context.MODE_PRIVATE) would create a file.

Android supports world readable or writable files, but it is considered good practice to keep files private to the application and use content provider if you want to share data with other applications.

The following example shows the API usage.

public class Util {
        public static void writeConfiguration(Context ctx ) {
                try (FileOutputStream openFileOutput =
                         ctx.openFileOutput( "config.txt", Context.MODE_PRIVATE);) {

                        openFileOutput.write("This is a test1.".getBytes());
                        openFileOutput.write("This is a test2.".getBytes());
                } catch (Exception e) {
                        // not handled
public void readFileFromInternalStorage(String fileName) {
        String eol = System.getProperty("line.separator");
        try (BufferedReader input = new BufferedReader(new InputStreamReader(
                openFileInput(fileName))); ){
          String line;
          StringBuffer buffer = new StringBuffer();
          while ((line = input.readLine()) != null) {
                buffer.append(line + eol);
        } catch (Exception e) {
                 // we do not care

6.2. External storage

Android supports also access to an external storage system e.g. the SD card. All files and directories on the external storage system are readable for all applications with the correct permission.

To read from external storage your application need to have the android.permission.READ_EXTERNAL_STORAGE permission.

To write to the external storage system your application needs the android.permission.WRITE_EXTERNAL_STORAGE permission. You get the path to the external storage system via the Environment.getExternalStorageDirectory() method.

Via the following method call you can check the state of the external storage system. If the Android device is connected via USB to a computer, a SD card which might be used for the external storage system is not available.


The following shows an example for reading from the external storage system.

private void readFileFromSDCard() {
        File directory = Environment.getExternalStorageDirectory();
        // assumes that a file article.rss is available on the SD card
        File file = new File(directory + "/article.rss");
        if (!file.exists()) {
                throw new RuntimeException("File not found");
        Log.e("Testing", "Starting to read");
        BufferedReader reader = null;
        try {
                reader = new BufferedReader(new FileReader(file));
                StringBuilder builder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
        } catch (Exception e) {
        } finally {
                if (reader != null) {
                        try {
                        } catch (IOException e) {

7. About this website

8.1. Android Resources

https://www.android.com/intl/de_de/ === vogella GmbH training and consulting support


The vogella company provides comprehensive training and education services from experts in the areas of Eclipse RCP, Android, Git, Java, Gradle and Spring. We offer both public and inhouse training. Whichever course you decide to take, you are guaranteed to experience what many before you refer to as “The best IT class I have ever attended”.

The vogella company offers expert consulting services, development support and coaching. Our customers range from Fortune 100 corporations to individual developers.

Copyright © 2012-2016 vogella GmbH. Free use of the software examples is granted under the terms of the EPL License. This tutorial is published under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany license.

See Licence.