Data storage in Android filesystem

In Android OS, application can have many options to store local data (offline, in filesystem). They are:

Shared Preferences

Application aspect:

  • Used to store primitive data (e.g. int, boolean, String…)
  • Key-value pairs. For example:
    • “address” -> “123 Wall Street”
    • “id” -> 132
    • “isPaid” -> true
  • Can’t be accessed by other apps.
  • Will be removed when user uninstall app.
  • How to use

Filesystem aspect:

  • All data is stored in XML files, located at:
    • /data/data/<app.package.name>/shared_prefs/*
  • Can be accessed by user with root privilege.

Internal Storage

Application aspect:

  • Used to store normal files/folders
  • Can’t be accessed by other apps.
  • Will be removed when user uninstall app.
  • How to use
    • Context.openFileInput() return FileInputStream
    • Context.openFileOutput() return FileOutputStream
    • read(), write(), close() as *InputStream

Filesystem aspect:

  • Data is stored as normal file, at:
    • /data/data/<app.package.name>/files/
  • Some APIs:
    • Context.getCacheDir() return File point to /data/data/<app.package.name>/caches
    • Context.getFilesDir() return File point to /data/data/<app.package.name>/files
    • Context.getDir(<dir_name>,<mode>) create and return File point to /data/data/<app.package.name>/app_<dir_name>

External Storage

There are 2 types:

  • Removable storage: like external SD Card (you can physical remove it).
  • Non-removable: on-board flash memory (NAND/NOR), partitioned to be used as external storage.

One device can have multi external storages (1 is called primary). From now on, assume that we use primary, and located at /sdcard.

Also pay attention to these permissions:

  • android.permission.WRITE_EXTERNAL_STORAGE
  • android.permission.READ_EXTERNAL_STORAGE

Application aspect:

  • Used to store normal files/folders
  • Can be accessed by other apps.
  • How to use

Filesystem aspect:

  • Public storage (system-wide access, won’t be deleted when uninstalling):
    • Environment.getExternalStorageDirectory() return File point to the top-level primary external storage directory. i.e. /sdcard. May leave garbage to user, should not use.
    • Environment.getExternalStoragePublicDirectory(<type>) return File point to some common public folder. i.e. /sdcard/Music, /sdcard/DCIM
  • Private storage API (app access, will be deleted when uninstalling):
    • Context.getExternalFilesDir(null) to get top-level dir. i.e. /sdcard/Android/<app.package.name>/files
    • Context.getExternalFilesDir(<type>) return File point to some common app-private folder. i.e. /sdcard/Android/<app.package.name>/files/Pictures

Database

TBD

One thought on “Data storage in Android filesystem

  1. Pingback: Android filesystem cheatsheet | MW

Leave a comment