Data Storage tutorial, basic samples are included

SDK Version: 

    Data Storage Methods

  • Preferences
  • Preferences is a lightweight mechanism to store and retrieve key-value pairs of primitive data types.
  • Files
  • You can store your data in files on your mobile phone, or in a removable storage medium.
  • Databases
  • Android Api supports SQLite databases. All databases, SQLite and others, are stored on the device in /data/data/package_name/databases.
  • Network
  • You can also use the Internet to store and receive data, whether it's an SQLite database, or just a simple textfile.



  1. // Restore preferences
  2. SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

"PREFS_NAME" is a String, for instance "myData"(.xml). You should know that it stores key- value pairs in .xml format.

  1. // Save preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
  2. SharedPreferences.Editor editor = settings.edit();
  3. // Don't forget to commit your edits!!!
  4. editor.commit();

That is it.

Writing to the SD Card:

  1. FileOutputStream fos = openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE);
  2. // Reading it back..
  3. FileInputStream fis = openFileInput(“sdcard/sdtext.txt”);

Writing to files with Serialization / writing Objects to file:

  1. FileOutputStream fos = context.openFileOutput(SAVENAME, context.MODE_PRIVATE);
  2. oos.writeObject(this); oos.close();
  3. // Reading it back..
  4. FileInputStream fis = context.openFileInput(SAVENAME);
  5. Flow f = (Flow) ois.readObject();

You can also use Internet to store your data. Here's an example code how can you upload your file(s) to you remote web server:

  1. File f = new File("/path/fileToUpload.txt");
  2. HttpRequest request = new HttpRequest("http://host/some_path");
  3. Part[] parts = { new StringPart("param_name", "value"), new FilePart(f.getName(), f) };
  4. filePost.setEntity( new MultipartRequestEntity(parts, filePost.getParams()) );
  5. HttpClient client = new HttpClient();
  6. int status = client.executeMethod(filePost);

Storing your data in databases are not that simple like store key-value pairs in Preferences. That's why I'm going to show you the Database method in a next tutorial.