Home | History | Annotate | Download | only in data
      1 page.title=Storage Options
      2 page.tags="database","sharedpreferences","sdcard"
      3 @jd:body
      4 
      5 
      6 <div id="qv-wrapper">
      7 <div id="qv">
      8 
      9   <h2>Storage quickview</h2>
     10   <ul>
     11     <li>Use Shared Preferences for primitive data</li>
     12     <li>Use internal device storage for private data</li>
     13     <li>Use external storage for large data sets that are not private</li>
     14     <li>Use SQLite databases for structured storage</li>
     15   </ul>
     16 
     17   <h2>In this document</h2>
     18   <ol>
     19     <li><a href="#pref">Using Shared Preferences</a></li>
     20     <li><a href="#filesInternal">Using the Internal Storage</a></li>
     21     <li><a href="#filesExternal">Using the External Storage</a></li>
     22     <li><a href="#db">Using Databases</a></li>
     23     <li><a href="#netw">Using a Network Connection</a></li>
     24   </ol>
     25 
     26   <h2>See also</h2>
     27   <ol>
     28     <li><a href="#pref">Content Providers and Content Resolvers</a></li>
     29   </ol>
     30 
     31 </div>
     32 </div>
     33 
     34 <p>Android provides several options for you to save persistent application data. The solution you
     35 choose depends on your specific needs, such as whether the data should be private to your
     36 application or accessible to other applications (and the user) and how much space your data
     37 requires.
     38 </p>
     39 
     40 <p>Your data storage options are the following:</p>
     41 
     42 <dl>
     43   <dt><a href="#pref">Shared Preferences</a></dt>
     44     <dd>Store private primitive data in key-value pairs.</dd>
     45   <dt><a href="#filesInternal">Internal Storage</a></dt>
     46     <dd>Store private data on the device memory.</dd>
     47   <dt><a href="#filesExternal">External Storage</a></dt>
     48     <dd>Store public data on the shared external storage.</dd>
     49   <dt><a href="#db">SQLite Databases</a></dt>
     50     <dd>Store structured data in a private database.</dd>
     51   <dt><a href="#netw">Network Connection</a></dt>
     52     <dd>Store data on the web with your own network server.</dd>
     53 </dl>
     54 
     55 <p>Android provides a way for you to expose even your private data to other applications
     56 &mdash; with a <a href="{@docRoot}guide/topics/providers/content-providers.html">content
     57 provider</a>. A content provider is an optional component that exposes read/write access to
     58 your application data, subject to whatever restrictions you want to impose. For more information
     59 about using content providers, see the
     60 <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
     61 documentation.
     62 </p>
     63 
     64 
     65 
     66 
     67 <h2 id="pref">Using Shared Preferences</h2>
     68 
     69 <p>The {@link android.content.SharedPreferences} class provides a general framework that allows you
     70 to save and retrieve persistent key-value pairs of primitive data types. You can use {@link
     71 android.content.SharedPreferences} to save any primitive data: booleans, floats, ints, longs, and
     72 strings. This data will persist across user sessions (even if your application is killed).</p>
     73 
     74 <div class="sidebox-wrapper">
     75 <div class="sidebox">
     76 <h3>User Preferences</h3>
     77 <p>Shared preferences are not strictly for saving "user preferences," such as what ringtone a
     78 user has chosen. If you're interested in creating user preferences for your application, see {@link
     79 android.preference.PreferenceActivity}, which provides an Activity framework for you to create
     80 user preferences, which will be automatically persisted (using shared preferences).</p>
     81 </div>
     82 </div>
     83 
     84 <p>To get a {@link android.content.SharedPreferences} object for your application, use one of
     85 two methods:</p>
     86 <ul>
     87   <li>{@link android.content.Context#getSharedPreferences(String,int)
     88 getSharedPreferences()} - Use this if you need multiple preferences files identified by name,
     89 which you specify with the first parameter.</li>
     90   <li>{@link android.app.Activity#getPreferences(int) getPreferences()} - Use this if you need
     91 only one preferences file for your Activity. Because this will be the only preferences file
     92 for your Activity, you don't supply a name.</li>
     93 </ul>
     94 
     95 <p>To write values:</p>
     96 <ol>
     97   <li>Call {@link android.content.SharedPreferences#edit()} to get a {@link
     98 android.content.SharedPreferences.Editor}.</li>
     99   <li>Add values with methods such as {@link
    100 android.content.SharedPreferences.Editor#putBoolean(String,boolean) putBoolean()} and {@link
    101 android.content.SharedPreferences.Editor#putString(String,String) putString()}.</li>
    102   <li>Commit the new values with {@link android.content.SharedPreferences.Editor#commit()}</li>
    103 </ol>
    104 
    105 <p>To read values, use {@link android.content.SharedPreferences} methods such as {@link
    106 android.content.SharedPreferences#getBoolean(String,boolean) getBoolean()} and {@link
    107 android.content.SharedPreferences#getString(String,String) getString()}.</p>
    108 
    109 <p>
    110 Here is an example that saves a preference for silent keypress mode in a
    111 calculator:
    112 </p>
    113 
    114 <pre>
    115 public class Calc extends Activity {
    116     public static final String PREFS_NAME = "MyPrefsFile";
    117 
    118     &#64;Override
    119     protected void onCreate(Bundle state){
    120        super.onCreate(state);
    121        . . .
    122 
    123        // Restore preferences
    124        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    125        boolean silent = settings.getBoolean("silentMode", false);
    126        setSilent(silent);
    127     }
    128 
    129     &#64;Override
    130     protected void onStop(){
    131        super.onStop();
    132 
    133       // We need an Editor object to make preference changes.
    134       // All objects are from android.context.Context
    135       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    136       SharedPreferences.Editor editor = settings.edit();
    137       editor.putBoolean("silentMode", mSilentMode);
    138 
    139       // Commit the edits!
    140       editor.commit();
    141     }
    142 }
    143 </pre>
    144 
    145 
    146 
    147 
    148 <a name="files"></a>
    149 <h2 id="filesInternal">Using the Internal Storage</h2>
    150 
    151 <p>You can save files directly on the device's internal storage. By default, files saved
    152 to the internal storage are private to your application and other applications cannot access
    153 them (nor can the user). When the user uninstalls your application, these files are removed.</p>
    154 
    155 <p>To create and write a private file to the internal storage:</p>
    156 
    157 <ol>
    158   <li>Call {@link android.content.Context#openFileOutput(String,int) openFileOutput()} with the
    159 name of the file and the operating mode. This returns a {@link java.io.FileOutputStream}.</li>
    160   <li>Write to the file with {@link java.io.FileOutputStream#write(byte[]) write()}.</li>
    161   <li>Close the stream with {@link java.io.FileOutputStream#close()}.</li>
    162 </ol>
    163 
    164 <p>For example:</p>
    165 
    166 <pre>
    167 String FILENAME = "hello_file";
    168 String string = "hello world!";
    169 
    170 FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
    171 fos.write(string.getBytes());
    172 fos.close();
    173 </pre>
    174 
    175 <p>{@link android.content.Context#MODE_PRIVATE} will create the file (or replace a file of
    176 the same name) and make it private to your application. Other modes available are: {@link
    177 android.content.Context#MODE_APPEND}, {@link
    178 android.content.Context#MODE_WORLD_READABLE}, and {@link
    179 android.content.Context#MODE_WORLD_WRITEABLE}.</p>
    180 
    181 <p>To read a file from internal storage:</p>
    182 
    183 <ol>
    184   <li>Call {@link android.content.Context#openFileInput openFileInput()} and pass it the
    185 name of the file to read. This returns a {@link java.io.FileInputStream}.</li>
    186   <li>Read bytes from the file with {@link java.io.FileInputStream#read(byte[],int,int)
    187 read()}.</li>
    188   <li>Then close the stream with  {@link java.io.FileInputStream#close()}.</li>
    189 </ol>
    190 
    191 <p class="note"><strong>Tip:</strong> If you want to save a static file in your application at
    192 compile time, save the file in your project <code>res/raw/</code> directory. You can open it with
    193 {@link android.content.res.Resources#openRawResource(int) openRawResource()}, passing the {@code
    194 R.raw.<em>&lt;filename&gt;</em>} resource ID. This method returns an {@link java.io.InputStream}
    195 that you can use to read the file (but you cannot write to the original file).
    196 </p>
    197 
    198 
    199 <h3 id="InternalCache">Saving cache files</h3>
    200 
    201 <p>If you'd like to cache some data, rather than store it persistently, you should use {@link
    202 android.content.Context#getCacheDir()} to open a {@link
    203 java.io.File} that represents the internal directory where your application should save
    204 temporary cache files.</p>
    205 
    206 <p>When the device is
    207 low on internal storage space, Android may delete these cache files to recover space. However, you
    208 should not rely on the system to clean up these files for you. You should always maintain the cache
    209 files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user
    210 uninstalls your application, these files are removed.</p>
    211 
    212 
    213 <h3 id="InternalMethods">Other useful methods</h3>
    214 
    215 <dl>
    216   <dt>{@link android.content.Context#getFilesDir()}</dt>
    217     <dd>Gets the absolute path to the filesystem directory where your internal files are saved.</dd>
    218   <dt>{@link android.content.Context#getDir(String,int) getDir()}</dt>
    219     <dd>Creates (or opens an existing) directory within your internal storage space.</dd>
    220   <dt>{@link android.content.Context#deleteFile(String) deleteFile()}</dt>
    221     <dd>Deletes a file saved on the internal storage.</dd>
    222   <dt>{@link android.content.Context#fileList()}</dt>
    223     <dd>Returns an array of files currently saved by your application.</dd>
    224 </dl>
    225 
    226 
    227 
    228 
    229 <h2 id="filesExternal">Using the External Storage</h2>
    230 
    231 <p>Every Android-compatible device supports a shared "external storage" that you can use to
    232 save files. This can be a removable storage media (such as an SD card) or an internal
    233 (non-removable) storage. Files saved to the external storage are world-readable and can
    234 be modified by the user when they enable USB mass storage to transfer files on a computer.</p>
    235 
    236 <p>It's possible that a device using a partition of the
    237 internal storage for the external storage may also offer an SD card slot. In this case,
    238 the SD card is <em>not</em> part of the external storage and your app cannot access it (the extra
    239 storage is intended only for user-provided media that the system scans).</p>
    240 
    241 <p class="caution"><strong>Caution:</strong> External storage can become unavailable if the user mounts the
    242 external storage on a computer or removes the media, and there's no security enforced upon files you
    243 save to the external storage. All applications can read and write files placed on the external
    244 storage and the user can remove them.</p>
    245 
    246 
    247 <h3 id="MediaAvail">Checking media availability</h3>
    248 
    249 <p>Before you do any work with the external storage, you should always call {@link
    250 android.os.Environment#getExternalStorageState()} to check whether the media is available. The
    251 media might be mounted to a computer, missing, read-only, or in some other state. For example,
    252 here's how you can check the availability:</p>
    253 
    254 <pre>
    255 boolean mExternalStorageAvailable = false;
    256 boolean mExternalStorageWriteable = false;
    257 String state = Environment.getExternalStorageState();
    258 
    259 if (Environment.MEDIA_MOUNTED.equals(state)) {
    260     // We can read and write the media
    261     mExternalStorageAvailable = mExternalStorageWriteable = true;
    262 } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    263     // We can only read the media
    264     mExternalStorageAvailable = true;
    265     mExternalStorageWriteable = false;
    266 } else {
    267     // Something else is wrong. It may be one of many other states, but all we need
    268     //  to know is we can neither read nor write
    269     mExternalStorageAvailable = mExternalStorageWriteable = false;
    270 }
    271 </pre>
    272 
    273 <p>This example checks whether the external storage is available to read and write. The
    274 {@link android.os.Environment#getExternalStorageState()} method returns other states that you
    275 might want to check, such as whether the media is being shared (connected to a computer), is missing
    276 entirely, has been removed badly, etc. You can use these to notify the user with more information
    277 when your application needs to access the media.</p>
    278 
    279 
    280 <h3 id="AccessingExtFiles">Accessing files on external storage</h3>
    281 
    282 <p>If you're using API Level 8 or greater, use {@link
    283 android.content.Context#getExternalFilesDir(String) getExternalFilesDir()} to open a {@link
    284 java.io.File} that represents the external storage directory where you should save your
    285 files. This method takes a <code>type</code> parameter that specifies the type of subdirectory you
    286 want, such as {@link android.os.Environment#DIRECTORY_MUSIC} and
    287 {@link android.os.Environment#DIRECTORY_RINGTONES} (pass <code>null</code> to receive
    288 the root of your application's file directory). This method will create the
    289 appropriate directory if necessary. By specifying the type of directory, you
    290 ensure that the Android's media scanner will properly categorize your files in the system (for
    291 example, ringtones are identified as ringtones and not music). If the user uninstalls your
    292 application, this directory and all its contents will be deleted.</p>
    293 
    294 <p>If you're using API Level 7 or lower, use {@link
    295 android.os.Environment#getExternalStorageDirectory()}, to open a {@link
    296 java.io.File} representing the root of the external storage. You should then write your data in the
    297 following directory:</p>
    298 <pre class="no-pretty-print classic">
    299 /Android/data/<em>&lt;package_name&gt;</em>/files/
    300 </pre>
    301 <p>The {@code <em>&lt;package_name&gt;</em>} is your Java-style package name, such as "{@code
    302 com.example.android.app}". If the user's device is running API Level 8 or greater and they
    303 uninstall your application, this directory and all its contents will be deleted.</p>
    304 
    305 
    306 <div class="sidebox-wrapper" style="margin-top:3em">
    307 <div class="sidebox">
    308 
    309 <h4>Hiding your files from the Media Scanner</h4>
    310 
    311 <p>Include an empty file named {@code .nomedia} in your external files directory (note the dot
    312 prefix in the filename). This will prevent Android's media scanner from reading your media
    313 files and including them in apps like Gallery or Music.</p>
    314 
    315 </div>
    316 </div>
    317 
    318 
    319 <h3 id="SavingSharedFiles">Saving files that should be shared</h3>
    320 
    321 <p>If you want to save files that are not specific to your application and that should <em>not</em>
    322 be deleted when your application is uninstalled, save them to one of the public directories on the
    323 external storage. These directories lay at the root of the external storage, such as {@code
    324 Music/}, {@code Pictures/}, {@code Ringtones/}, and others.</p>
    325 
    326 <p>In API Level 8 or greater, use {@link
    327 android.os.Environment#getExternalStoragePublicDirectory(String)
    328 getExternalStoragePublicDirectory()}, passing it the type of public directory you want, such as
    329 {@link android.os.Environment#DIRECTORY_MUSIC}, {@link android.os.Environment#DIRECTORY_PICTURES},
    330 {@link android.os.Environment#DIRECTORY_RINGTONES}, or others. This method will create the
    331 appropriate directory if necessary.</p>
    332 
    333 <p>If you're using API Level 7 or lower, use {@link
    334 android.os.Environment#getExternalStorageDirectory()} to open a {@link java.io.File} that represents
    335 the root of the external storage, then save your shared files in one of the following
    336 directories:</p>
    337 
    338 <ul class="nolist"></li>
    339   <li><code>Music/</code> - Media scanner classifies all media found here as user music.</li>
    340   <li><code>Podcasts/</code> - Media scanner classifies all media found here as a podcast.</li>
    341   <li><code>Ringtones/ </code> - Media scanner classifies all media found here as a ringtone.</li>
    342   <li><code>Alarms/</code> - Media scanner classifies all media found here as an alarm sound.</li>
    343   <li><code>Notifications/</code> - Media scanner classifies all media found here as a notification
    344 sound.</li>
    345   <li><code>Pictures/</code> - All photos (excluding those taken with the camera).</li>
    346   <li><code>Movies/</code> - All movies (excluding those taken with the camcorder).</li>
    347   <li><code>Download/</code> - Miscellaneous downloads.</li>
    348 </ul>
    349 
    350 
    351 <h3 id="ExternalCache">Saving cache files</h3>
    352 
    353 <p>If you're using API Level 8 or greater, use {@link
    354 android.content.Context#getExternalCacheDir()} to open a {@link java.io.File} that represents the
    355 external storage directory where you should save cache files. If the user uninstalls your
    356 application, these files will be automatically deleted. However, during the life of your
    357 application, you should manage these cache files and remove those that aren't needed in order to
    358 preserve file space.</p>
    359 
    360 <p>If you're using API Level 7 or lower, use {@link
    361 android.os.Environment#getExternalStorageDirectory()} to open a {@link java.io.File} that represents
    362 the root of the external storage, then write your cache data in the following directory:</p>
    363 <pre class="no-pretty-print classic">
    364 /Android/data/<em>&lt;package_name&gt;</em>/cache/
    365 </pre>
    366 <p>The {@code <em>&lt;package_name&gt;</em>} is your Java-style package name, such as "{@code
    367 com.example.android.app}".</p>
    368 
    369 
    370 
    371 <h2 id="db">Using Databases</h2>
    372 
    373 <p>Android provides full support for <a href="http://www.sqlite.org/">SQLite</a> databases.
    374 Any databases you create will be accessible by name to any
    375 class in the application, but not outside the application.</p>
    376 
    377 <p>The recommended method to create a new SQLite database is to create a subclass of {@link
    378 android.database.sqlite.SQLiteOpenHelper} and override the {@link
    379 android.database.sqlite.SQLiteOpenHelper#onCreate(SQLiteDatabase) onCreate()} method, in which you
    380 can execute a SQLite command to create tables in the database. For example:</p>
    381 
    382 <pre>
    383 public class DictionaryOpenHelper extends SQLiteOpenHelper {
    384 
    385     private static final int DATABASE_VERSION = 2;
    386     private static final String DICTIONARY_TABLE_NAME = "dictionary";
    387     private static final String DICTIONARY_TABLE_CREATE =
    388                 "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
    389                 KEY_WORD + " TEXT, " +
    390                 KEY_DEFINITION + " TEXT);";
    391 
    392     DictionaryOpenHelper(Context context) {
    393         super(context, DATABASE_NAME, null, DATABASE_VERSION);
    394     }
    395 
    396     &#64;Override
    397     public void onCreate(SQLiteDatabase db) {
    398         db.execSQL(DICTIONARY_TABLE_CREATE);
    399     }
    400 }
    401 </pre>
    402 
    403 <p>You can then get an instance of your {@link android.database.sqlite.SQLiteOpenHelper}
    404 implementation using the constructor you've defined. To write to and read from the database, call
    405 {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase()} and {@link
    406 android.database.sqlite.SQLiteOpenHelper#getReadableDatabase()}, respectively. These both return a
    407 {@link android.database.sqlite.SQLiteDatabase} object that represents the database and
    408 provides methods for SQLite operations.</p>
    409 
    410 <div class="sidebox-wrapper">
    411 <div class="sidebox">
    412 <p>Android does not impose any limitations beyond the standard SQLite concepts. We do recommend
    413 including an autoincrement value key field that can be used as a unique ID to
    414 quickly find a record.  This is not required for private data, but if you
    415 implement a <a href="{@docRoot}guide/topics/providers/content-providers.html">content provider</a>,
    416 you must include a unique ID using the {@link android.provider.BaseColumns#_ID BaseColumns._ID}
    417 constant.
    418 </p>
    419 </div>
    420 </div>
    421 
    422 <p>You can execute SQLite queries using the {@link android.database.sqlite.SQLiteDatabase}
    423 {@link
    424 android.database.sqlite.SQLiteDatabase#query(boolean,String,String[],String,String[],String,String,String,String)
    425 query()} methods, which accept various query parameters, such as the table to query,
    426 the projection, selection, columns, grouping, and others. For complex queries, such as
    427 those that require column aliases, you should use
    428 {@link android.database.sqlite.SQLiteQueryBuilder}, which provides
    429 several convienent methods for building queries.</p>
    430 
    431 <p>Every SQLite query will return a {@link android.database.Cursor} that points to all the rows
    432 found by the query. The {@link android.database.Cursor} is always the mechanism with which
    433 you can navigate results from a database query and read rows and columns.</p>
    434 
    435 <p>For sample apps that demonstrate how to use SQLite databases in Android, see the
    436 <a href="{@docRoot}resources/samples/NotePad/index.html">Note Pad</a> and
    437 <a href="{@docRoot}resources/samples/SearchableDictionary/index.html">Searchable Dictionary</a>
    438 applications.</p>
    439 
    440 
    441 <h3 id="dbDebugging">Database debugging</h3>
    442 
    443 <p>The Android SDK includes a {@code sqlite3} database tool that allows you to browse
    444 table contents, run SQL commands, and perform other useful functions on SQLite
    445 databases.  See <a href="{@docRoot}tools/help/adb.html#sqlite">Examining sqlite3
    446 databases from a remote shell</a> to learn how to run this tool.
    447 </p>
    448 
    449 
    450 
    451 
    452 
    453 <h2 id="netw">Using a Network Connection</h2>
    454 
    455 <!-- TODO MAKE THIS USEFUL!! -->
    456 
    457 <p>You can use the network (when it's available) to store and retrieve data on your own web-based
    458 services. To do network operations, use classes in the following packages:</p>
    459 
    460 <ul class="no-style">
    461   <li><code>{@link java.net java.net.*}</code></li>
    462   <li><code>{@link android.net android.net.*}</code></li>
    463 </ul>
    464