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