Tutorial details

Android Persistence with preferences and files | App Code for Sale | Preview

Android Persistence with preferences and files | Android Tutorial

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. It is based on Eclipse 3.7, Java 1.6 and Android 4.1 (Ice Cream Sandwich).

Overview PAGE TOP

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. It is based on Eclipse 3.7, Java 1.6 and Android 4.1 (Ice Cream Sandwich).


http://www.vogella.de under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany (CC BY-NC-SA 3.0) licence.

Android File Based Persistence PAGE TOP

Methods of persistence

Android allows to store local data as files. Android uses file based storage for handling application settings (Preferences) and instances of the SQLite database.

For each application the Android system creates a data/data/package.of.the.application directory.

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 filesystem which contains file, cache files and preferences.


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.

Internal vs. external storage

Android has internal storage and external storage. External storage is not private and may not always be available.

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.

Preferences PAGE TOP


Android supports the usage of Preferences for persisting key-values pairs in the Android file system.

The definition of Preferences can be done via an XML resource.

The PreferenceManager gives access to the preference values. The following code shows how to access your default preferences.

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 

Values can get accessed via the key of the preference setting.

String username = preferences.getString("username", "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 commit() method to apply your changes.

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

Preference Values

Android allows to create XML fileswhich describes the preferences which should be entered. From this XML file the user interface is automatically generated and the values are stored automatically by Android.

To create such a file, select File → New → Android → Android XML File and select the Preference as Resource Type.


Android provides the PreferenceFragment class which simplifies the creation of an user interface for maintaining preference values. This fragment can load an XML preference definition file via the method addPreferencesFromResource().

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. .

Tutorial: Prerequirements PAGE TOP

Using preferences

We will continue using the example project "de.vogella.android.social".

Create an Android XML resource called preferences.xml of the PreferenceScreen type.


Open the file via right-mouse click and Open with → Android XML Resource Editor. Press Add, add a PreferenceCategory and add two preferences of type EditTextPreferences. They should be called User and Password.




You can also enter values for other properties of EditTextField, e.g. the inputMethod.

Add the following attribute to the XML definition of your password field to make the input quoted with *.


Create the class MyPreferencesActivity which extends PreferenceActivity. This Activity will load the preference.xml file and will allow the user to change package de.vogella.android.socialapp;

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

public class MyPreferencesActivity extends PreferenceActivity {
  public void onCreate(Bundle savedInstanceState) {
}the values.

To make this class available as an activity for Android you need to register it in your AndroidManifest.xml file. Select AndroidManifest.xml and the Application tab. Scroll to the bottom of the view and add your new Activity via the Add button.


To make use of our new preference activity and the preference values we adjust the "OverviewActivity". The first button will show the current values of the preferences via a Toast and the second button will revert the maintained user name to demonstrate how you could change the preferences via code.

    package de.vogella.android.socialapp;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class OverviewActivity extends Activity {
  SharedPreferences preferences;
  public void onCreate(Bundle savedInstanceState) {
    Button button = (Button) findViewById(R.id.Button01);
    // Initialize preferences
    preferences = PreferenceManager.getDefaultSharedPreferences(this);

    button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        String username = preferences.getString("username", "n/a");
        String password = preferences.getString("password", "n/a");
        showPrefs(username, password);

    Button buttonChangePreferences = (Button) findViewById(R.id.Button02);
    buttonChangePreferences.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {


  private void showPrefs(String username, String password){
        "Input: " + username + " and password: "
            + password, Toast.LENGTH_LONG).show();


  private void updatePreferenceValue(){
    Editor edit = preferences.edit();
    String username = preferences.getString("username", "n/a");
    // We will just revert the current user name and save again
    StringBuffer buffer = new StringBuffer();
    for (int i = username.length() - 1; i >= 0; i--) {
    edit.putString("username", buffer.toString());
    // A toast is a view containing a quick little message for the
    // user. We give a little feedback
        "Reverted string sequence of user name.",

To open the new preference Activity we will use the onOptionsItemSelected() method. Even though we currently have only one option in our menu we use a switch to be ready for several new menu entries. To see the current values of the preferences we define a button and use the class PreferenceManager to get the sharedPreferences.

public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.mainmenu, menu);
  return true;

// This method is called once the menu is selected
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
  // We have only one menu option
  case R.id.preferences:
    // Launch Preference activity
    Intent i = new Intent(OverviewActivity.this, MyPreferencesActivity.class);
    // Some feedback to the user
    Toast.makeText(OverviewActivity.this, "Enter your user credentials.",

  return true;


Run your application. Select from your ActionBar the Preference menu entry. You should be able to enter your user settings then press the back hardware button to return to your main activity. The saved values should be displayed in a small message windows (Toast) if you press your first button. If you press the second button the username should be reversed.


Android File API PAGE TOP


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, int) would create a file.

int specifies the permissions which are:

  • MODE_PRIVATE - No access for other applications
  • MODEWORLDREADABLE - Read access for other applications
  • MODEWORLDWRITABLE - Write access for other applications

The following example shows the API usage.

private void writeFileToInternalStorage() {
  String eol = System.getProperty("line.separator");
  BufferedWriter writer = null;
  try {
    writer = new BufferedWriter(new OutputStreamWriter(openFileOutput("myfile", MODE_WORLD_WRITEABLE)));
    writer.write("This is a test1." + eol);
    writer.write("This is a test2." + eol);
  } catch (Exception e) {
  } finally {
    if (writer != null) {
    try {
    } catch (IOException e) {

private void readFileFromInternalStorage() {
  String eol = System.getProperty("line.separator");
  BufferedReader input = null;
  try {
    input = new BufferedReader(new InputStreamReader(openFileInput("myfile")));
    String line;
    StringBuffer buffer = new StringBuffer();
    while ((line = input.readLine()) != null) {
    buffer.append(line + eol);
  } catch (Exception e) {
  } finally {
  if (input != null) {
    try {
    } catch (IOException e) {

How to access a shared file

Another application can access a file, which has been created with the MODEWORLDREADABLE model. For this, it need to knows the package and file name. The following example shows this.

FileInputStream openFileInput = createPackageContext("the_package", 0).openFileInput("thefile"); 

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.READEXTERNALSTORAGE permission.

To write to the external storage system your application needs the android.permission.WRITEEXTERNALSTORAGE 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) {
18 Comments Leave a comment

Please login in order to leave a comment.

Newest first
  • fehelfertjohn 2015-03-21 11:33:12 Thread #448

    wedding dresses dress for wedding
    luxury wedding dresses

    Sexy A-Line Scoop Beaded Hollow Out Mother of the Bride Dress - $140.00 : Professional wedding dresses stores, luxuryweddingdress.org language: Deutsch Français italiano Español Português 日本語 russian arabic norwegian swedish danish Nederlands finland ireland English Payment | Shipping & Returns | Wholesale | Contact Us Welcome! Sign In or Register Your cart is empty Powered by Zen Cart :: The Art of E-Commerce


    US Dollar Euro GB Pound Canadian Dollar Australian Dollar Jappen Yen Norske Krone Swedish Krone Danish Krone CNY


    Special Occasion Dresses Wedding Apparel Bridesmaid Dresses Flower Girl Dresses Mother of the Bride Dresses Designer Mother of the Bride Dresses Latest Mother Dresses Mother of the Bride Dresses 2014 Vintage Mother Dresses Wedding Dresses

    Featured - [more]

    Fancy Rhinestone Beaded Sweetheart Floor Length Red Wedding DressFancy Rhinestone Beaded Sweetheart Floor Length Red Wedding Dress$689.00 $229.00
    Save: 67% off Fashion Sweetheart Asymmetry Flower Appliques Zipper-Up Evening DressFashion Sweetheart Asymmetry Flower Appliques Zipper-Up Evening Dress$475.00 $150.00
    Save: 68% off Vintage Bateau Neck Sheer Short Sleeve Floor Length A-Line Wedding DressVintage Bateau Neck Sheer Short Sleeve Floor Length A-Line Wedding Dress$999.00 $379.00
    Save: 62% off Home :: Wedding Apparel :: Mother of the Bride Dresses :: Vintage Mother Dresses :: Sexy A-Line Scoop Beaded Hollow Out Mother of the Bride Dress .jqzoom{ float:left; position:relative; padding:0px; cursor:pointer; width:301px; height:406px; } Sexy A-Line Scoop Beaded Hollow Out Mother of the Bride Dress Sexy A-Line Scoop Beaded Hollow Out Mother of the Bride Dress $331.00 $140.00
    Save: 58% off

    Please Choose:


    Custom Size Please Select Size US 10 US 12 US 14 US 14W US 16 US 16W US 18W US 2 US 20W US 22W US 24W US 26W US 4 US 6 US 8 Size


    Black Blue Bright Rust Red Brown Bud Green Burgundy Champagne Chocolate Daffodil Dark Brown Dark Green Dark Navy Dark Royal Blue Fuchsia Golden Grape Green Hunter Ice Blue Ivory Kelly Lavender Light Plum Light Sky Blue Lilac Mint Orange Red Org Pearl Pink Pink Please Select Color Purple Red Regency Royal Blue Sage Same As First Picture Silver Skin Pink Watermelon White Color

    Add to Cart:

    • Product Name:

      Sexy A-Line Scoop Beaded Hollow Out Mother of the Bride Dress

    • Category: Wedding Apparel > Mother of the Bride Dresses > Vintage Mother Dresses
    • Gross Weight/Package: 1.50( kg )
    • Clean: Dry Clean Only


    The price is just for the dress. Any other accessories in the picture, just like veil, jacket, etc. are not included, and if you need one, please feel free to contact us.






    Related Products

    Sexy A-Line Scoop Beaded Hollow Out Mother of the Bride DressSexy A-Line Scoop Beaded Hollow Out Mother of the Bride Dress Write Review
    Wedding Dresses Bridesmaid Dresses Mother & Guests Dresses Flower Girl Dresses Weekly Specials Copyright © 2012 All Rights Reserved. wedding dresses outlet
    wedding dresses online
    to look for matches set in an very old store.Yow will discover antique outlet stores most anywhere plus online.When viewing vintage orientate jewelry don't forget to check the jewelry over to make certain there isn't an missing boulders or abnormal wear.

    With no any heirloom jewelry next it's under your control by necklaces and make heirlooms for use on your children.One thing you ought to consider is the grade of the gear and how long they'll last in time.Wedding jewelry doesn't need be expensive but if you need handed down to future generations you must buy whatever will very last.

    Here's some how to choose a really perfect wedding jewellery:

    One concern when getting jewelry will be the shape on your face.For people with a extensive jaw and you wish to choose jewelry of which does not call attention to this.So she should choose longer looking jewelry that include necklaces using long durant lariat not to mention long bracelets.

    It's a person's hairstyle is without a doubt another consideration for everybody who is wearing a long do you wish to be sure that you earrings can be found if you have been wearing your hair out afterward small earrings could possibly be consideration.However if you'd like to accentuate the knack then you certainly probably just want to wear some terrific chandelier jewelry or extensive Drippy bare duster's.

    You ought to keep any jewelry beautiful and easy.You just want to jewelry to accentuate present but never overshadow typically the beautiful glow within the bride.

    Many brides judgemental whether people like magical or gold if you'd like to spend a lot of cash you can pick sterling silver that is certainly an important shiny together with beautiful when gold.Jewels, of tutorial, are always the best choice if available for you many other gemstones to add some color into the day.Just guantee that the jewelry won't draw attention off the lovely bridal apparel.

    Pearls would definitely be a traditional engagement jewelry choice.They check great together with enhance any sort of complexion and always match perfect while using bridal clothing.Even if your brightest deciding on off-white youre able to choose cream-colored pearls for use on your wedding jewelry and still have a classy look.

    Whichever you choose for wedding jewelry you wish to be for sure to care for them properly to help you last for years to come.While diamonds are tough and aren't easily damaged pearls and also other gemstones are actually softer and you've got to handle them after due thought.Be certain to keep them within the protected section where that they can't rub up against other jewelry and become scratched.Always be thoughtful when cleaning just about any pearls or gemstones you don't use nasty chemicals that might damage a stone.Periodic cleaning with all the proper strategies can go one making your jewels last your life.

    Choosing an individual's wedding jewelry must be among the many fun tasks on your wedding considering.Be sure to pick jewelry that one could wear for other occasions with your wedding jewels have invariably been a reminder of one's beautiful evening.

    apparel blog


    About luxuryweddingdress.org blog

  • fehelfertjohn 2015-03-21 11:32:18 Thread #446
  • fehelfertjohn 2015-03-21 11:32:00 Thread #445

    top brand watches | replica swiss watches | top brand watches

    Replica JUVENIA watches

    language: Deutsch   Français   italiano   Español   Português   日本語   russian   arabic   norwegian   swedish   danish   Nederlands   finland   ireland   English  

    <div id="navBreadCrumb">  <a href="http://www.agwatches.com/">Home</a>&nbsp;::&nbsp;

    JUVENIA watches

    JUVENIA watches

    Filter Results by: Items starting with ... A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9

    .articles{width:900px; margin:0 auto;} .articles ul{width:900px; } .articles li{width:450px; float:left;}

    <div  class="articles">
        <li><a href="http://www.agwatches.com/index.php?main_page=page_2&article_id=1016" target="_blank">Antoine Martin Tourbillon Astronomique shows off at Baselworld</a></li>
        <li><a href="http://www.agwatches.com/index.php?main_page=page_2&article_id=1015" target="_blank">Omega Replica,Omega Replica Watches,Replica Omega Watches</a></li>
        <li><a href="http://www.agwatches.com/index.php?main_page=page_2&article_id=1014" target="_blank">Confidence US |</a></li>
        <li><a href="http://www.agwatches.com/index.php?main_page=page_2&article_id=1013" target="_blank">Two Swiss Tag Heuer watches stolen during burglary in Charing, Ashford, on Friday, March 28</a></li>
        <li><a href="http://www.agwatches.com/index.php?main_page=page_2&article_id=1012" target="_blank">Swiss Replica Watches </a></li>
        <li><a href="http://www.agwatches.com/index.php?main_page=page_2&article_id=1011" target="_blank">Team Chevy Corvette DP's head to Long Beach | News | Motorsport.com</a></li>
        <li><a href="http://www.agwatches.com/index.php?main_page=page_2&article_id=1010" target="_blank">Replica Omega Seamaster Watches UK | AAA Quality Omega Seamaster For Sale</a></li>
        <li><a href="http://www.agwatches.com/index.php?main_page=page_2&article_id=1009" target="_blank">Taylor Kaye’s KiSS 92.5 Weekly Gossip Roundup: March 22, 2014 | CityNews</a></li>
        <li><a href="http://www.agwatches.com/index.php?main_page=page_2&article_id=1008" target="_blank">Longines watches </a></li>
        <li><a href="http://www.agwatches.com/index.php?main_page=page_2&article_id=1007" target="_blank">Detroit&#8217;s Watch Startup Shinola Featured In Aol&#8217;s &#8220;This Built America&#8221; Inaugural Episode | TechCrunch</a></li>
        <li><a href="http://www.agwatches.com/index.php?main_page=page_2" target="_blank">More News</a></li>

    1:1 replica watches
    Replica Ulysse-nardin watches

    watches blog


    About agwatches.com blog

  • fehelfertjohn 2015-03-21 11:31:23 Thread #444
  • fehelfertjohn 2015-03-21 11:31:01 Thread #443

    Discount Christian Louboutin Louis Womens High Top Leather Sneakers Black - $139.00 : Christian Louboutin outlet, christianlouboutinoutletus.org

    language: Deutsch   Français   italiano   Español   Português   日本語   russian   arabic   norwegian   swedish   danish   Nederlands   finland   ireland   English  

    .jqzoom{ float:left; position:relative; padding:0px; cursor:pointer; width:301px; height:300px; }
    Discount Christian Louboutin Louis Womens High Top Leather Sneakers Black
    Discount Christian Louboutin Louis Womens High Top Leather Sneakers Black
    $755.00  $139.00
    Save: 82% off

    Please Choose:


    US10UK7EUR4027cm US6UK3EUR3623cm US7UK4EUR3724cm US8UK5EUR3825cm US9UK6EUR3926cm

    Add to Cart:

    Christian Louboutin shoes includes many important silhouettes like wedges, flats, strappy heels and Christian Louboutin womens sneakers with key trend details like bright colorblocking, unique designes. Christian Louboutin Women Sneakers are popular with the unique design and luxurious appearance. And Christian Louboutin Louis Sneakers are a new creative design can be suitable for wearers in all seasons,such as Christian Louboutin Louis Womens High Top Leather Sneakers Black.The unique design could make you look more attractive and fashion.You can wear them when you running,playing golf,and so on.This Christian Louboutin Louis hi-top womens sneakers can be very comfortable.Christian Louboutin Bianca you may also interested in.
    Color: Black
    Material: Glossy sheepskin leather upper
    Flat heel
    Signature red leather sole<br/><br/>Christian Louboutin is a French footwear designer who launched his line of high-end women's shoes in France in 1991. Since 1992, his designs have incorporated the shiny, red-lacquered soles that have become his signature. The designer's professed goal is to "make a woman look sexy, beautiful, to make her legs look as long as can." While he does offer some lower-heeled styles, Louboutin is generally associated with his dressier evening-wear designs incorporating jeweled straps, bows, feathers, patent leather and other similar decorative touches.


    christian louboutin shoes for cheap
    christian louboutin sale

    sale blog


    About christianlouboutinoutletus.org blog

  • fehelfertjohn 2015-03-21 11:10:11 Thread #441

    timberland boots on sale | timberland boots | timberland boots for women

    Black Mens Timberland Boots 6 Inch [timberland23741] - $115.00 : Timberland outlet, timberlandbootsonlines.org

    language: Deutsch   Français   italiano   Español   Português   日本語   russian   arabic   norwegian   swedish   danish   Nederlands   finland   ireland   English  

    <div id="navBreadCrumb">  <a href="http://www.timberland-uk-boots.com/">Home</a>&nbsp;::&nbsp;

    Timberland Mens ::  Black Mens Timberland Boots 6 Inch

    .jqzoom{ float:left; position:relative; padding:0px; cursor:pointer; width:301px; height:300px; }
    Black Mens Timberland Boots 6 Inch
    Black Mens Timberland Boots 6 Inch
    $160.00  $115.00
    Save: 28% off

    Please Choose:


    -- Please Select -- us10=uk9.5=eu44 us6=uk5.5=eu39 us7.5=uk7=eu41 us7=uk6.5=eu40 us8.5=uk8=eu42 us9=uk8.5=eu43

    Add to Cart:

    Black Mens Timberland Boots 6 Inch


    Sale Cheap Black Mens Timberland Boots 6 Inch in timberland online shop with top quality, best services, best price! all Timberland 6 Inch are provided by professional manufactory directly, fast shipping once we have received yuro order, 7 days return and exchange accepted, 30 days money back warranty! take yuro favourite Timberland 6 Inch from us now!



    • Model: timberland23741

    timberland 6 inch
    timberland kids boots outlet

    sale blog


    About timberland-uk-boots.com blog


    Sign-in to your Chupamobile Account.

    The Easiest way to Launch your next App or Game.

    Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

    Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.