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 — 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 @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 @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 class="note"><strong>Note:</strong> The constants {@link 182 android.content.Context#MODE_WORLD_READABLE} and {@link 183 android.content.Context#MODE_WORLD_WRITEABLE} have been deprecated since API level 17. 184 Starting from Android N their use will result in a {@link java.lang.SecurityException} 185 to be thrown. 186 This means that apps targeting Android N and higher 187 cannot share private files by name, and attempts to share a "file://" URI will result in a 188 {@link android.os.FileUriExposedException} to be thrown. If your app needs to share private 189 files with other apps, it may use a {@link android.support.v4.content.FileProvider} with 190 the {@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION}. 191 See also <a 192 href="{@docRoot}training/secure-file-sharing/index.html">Sharing Files</a>. 193 </p> 194 195 <p>To read a file from internal storage:</p> 196 197 <ol> 198 <li>Call {@link android.content.Context#openFileInput openFileInput()} and pass it the 199 name of the file to read. This returns a {@link java.io.FileInputStream}.</li> 200 <li>Read bytes from the file with {@link java.io.FileInputStream#read(byte[],int,int) 201 read()}.</li> 202 <li>Then close the stream with {@link java.io.FileInputStream#close()}.</li> 203 </ol> 204 205 <p class="note"><strong>Tip:</strong> If you want to save a static file in your application at 206 compile time, save the file in your project <code>res/raw/</code> directory. You can open it with 207 {@link android.content.res.Resources#openRawResource(int) openRawResource()}, passing the 208 <code>R.raw.<em><filename></em></code> resource ID. This method returns an {@link java.io.InputStream} 209 that you can use to read the file (but you cannot write to the original file). 210 </p> 211 212 213 <h3 id="InternalCache">Saving cache files</h3> 214 215 <p>If you'd like to cache some data, rather than store it persistently, you should use {@link 216 android.content.Context#getCacheDir()} to open a {@link 217 java.io.File} that represents the internal directory where your application should save 218 temporary cache files.</p> 219 220 <p>When the device is 221 low on internal storage space, Android may delete these cache files to recover space. However, you 222 should not rely on the system to clean up these files for you. You should always maintain the cache 223 files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user 224 uninstalls your application, these files are removed.</p> 225 226 227 <h3 id="InternalMethods">Other useful methods</h3> 228 229 <dl> 230 <dt>{@link android.content.Context#getFilesDir()}</dt> 231 <dd>Gets the absolute path to the filesystem directory where your internal files are saved.</dd> 232 <dt>{@link android.content.Context#getDir(String,int) getDir()}</dt> 233 <dd>Creates (or opens an existing) directory within your internal storage space.</dd> 234 <dt>{@link android.content.Context#deleteFile(String) deleteFile()}</dt> 235 <dd>Deletes a file saved on the internal storage.</dd> 236 <dt>{@link android.content.Context#fileList()}</dt> 237 <dd>Returns an array of files currently saved by your application.</dd> 238 </dl> 239 240 241 242 243 <h2 id="filesExternal">Using the External Storage</h2> 244 245 <p>Every Android-compatible device supports a shared "external storage" that you can use to 246 save files. This can be a removable storage media (such as an SD card) or an internal 247 (non-removable) storage. Files saved to the external storage are world-readable and can 248 be modified by the user when they enable USB mass storage to transfer files on a computer.</p> 249 250 <p class="caution"><strong>Caution:</strong> External storage can become unavailable if the user mounts the 251 external storage on a computer or removes the media, and there's no security enforced upon files you 252 save to the external storage. All applications can read and write files placed on the external 253 storage and the user can remove them.</p> 254 255 <h3 id="ScopedDirAccess">Using Scoped Directory Access</h3> 256 257 On Android 7.0 or later, if you need access to a specific directory on 258 external storage, use scoped directory access. Scoped directory access 259 simplifies how your application accesses standard external storage directories, 260 such as the <code>Pictures</code> directory, and provides a simple 261 permissions UI that clearly details what directory the application is 262 requesting access to. For more details on scoped directory access, see 263 <a href="{@docRoot}training/articles/scoped-directory-access.html">Using 264 Scoped Directory Access</a>. 265 266 <h3 id="ExternalPermissions">Getting access to external storage</h3> 267 268 <p>In order to read or write files on the external storage, your app must acquire the 269 {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} 270 or {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} system 271 permissions. For example:</p> 272 <pre> 273 <manifest ...> 274 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 275 ... 276 </manifest> 277 </pre> 278 279 <p>If you need to both read and write files, then you need to request only the 280 {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} permission, because it 281 implicitly requires read access as well.</p> 282 283 <p class="note"><strong>Note:</strong> Beginning with Android 4.4, these permissions are not 284 required if you're reading or writing only files that are private to your app. For more 285 information, see the section below about 286 <a href="#AccessingExtFiles">saving files that are app-private</a>.</p> 287 288 289 290 <h3 id="MediaAvail">Checking media availability</h3> 291 292 <p>Before you do any work with the external storage, you should always call {@link 293 android.os.Environment#getExternalStorageState()} to check whether the media is available. The 294 media might be mounted to a computer, missing, read-only, or in some other state. For example, 295 here are a couple methods you can use to check the availability:</p> 296 297 <pre> 298 /* Checks if external storage is available for read and write */ 299 public boolean isExternalStorageWritable() { 300 String state = Environment.getExternalStorageState(); 301 if (Environment.MEDIA_MOUNTED.equals(state)) { 302 return true; 303 } 304 return false; 305 } 306 307 /* Checks if external storage is available to at least read */ 308 public boolean isExternalStorageReadable() { 309 String state = Environment.getExternalStorageState(); 310 if (Environment.MEDIA_MOUNTED.equals(state) || 311 Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 312 return true; 313 } 314 return false; 315 } 316 </pre> 317 318 <p>The {@link android.os.Environment#getExternalStorageState()} method returns other states that you 319 might want to check, such as whether the media is being shared (connected to a computer), is missing 320 entirely, has been removed badly, etc. You can use these to notify the user with more information 321 when your application needs to access the media.</p> 322 323 324 <h3 id="SavingSharedFiles">Saving files that can be shared with other apps</h3> 325 326 <div class="sidebox-wrapper" > 327 <div class="sidebox"> 328 329 <h4>Hiding your files from the Media Scanner</h4> 330 331 <p>Include an empty file named {@code .nomedia} in your external files directory (note the dot 332 prefix in the filename). This prevents media scanner from reading your media 333 files and providing them to other apps through the {@link android.provider.MediaStore} 334 content provider. However, if your files are truly private to your app, you should 335 <a href="#AccessingExtFiles">save them in an app-private directory</a>.</p> 336 337 </div> 338 </div> 339 340 <p>Generally, new files that the user may acquire through your app should be saved to a "public" 341 location on the device where other apps can access them and the user can easily copy them from the 342 device. When doing so, you should use to one of the shared public directories, such as {@code 343 Music/}, {@code Pictures/}, and {@code Ringtones/}.</p> 344 345 <p>To get a {@link java.io.File} representing the appropriate public directory, call {@link 346 android.os.Environment#getExternalStoragePublicDirectory(String) 347 getExternalStoragePublicDirectory()}, passing it the type of directory you want, such as 348 {@link android.os.Environment#DIRECTORY_MUSIC}, {@link android.os.Environment#DIRECTORY_PICTURES}, 349 {@link android.os.Environment#DIRECTORY_RINGTONES}, or others. By saving your files to the 350 corresponding media-type directory, 351 the system's media scanner can properly categorize your files in the system (for 352 instance, ringtones appear in system settings as ringtones, not as music).</p> 353 354 355 <p>For example, here's a method that creates a directory for a new photo album in 356 the public pictures directory:</p> 357 358 <pre> 359 public File getAlbumStorageDir(String albumName) { 360 // Get the directory for the user's public pictures directory. 361 File file = new File(Environment.getExternalStoragePublicDirectory( 362 Environment.DIRECTORY_PICTURES), albumName); 363 if (!file.mkdirs()) { 364 Log.e(LOG_TAG, "Directory not created"); 365 } 366 return file; 367 } 368 </pre> 369 370 371 372 <h3 id="AccessingExtFiles">Saving files that are app-private</h3> 373 374 <p>If you are handling files that are not intended for other apps to use 375 (such as graphic textures or sound effects used by only your app), you should use 376 a private storage directory on the external storage by calling {@link 377 android.content.Context#getExternalFilesDir(String) getExternalFilesDir()}. 378 This method also takes a <code>type</code> argument to specify the type of subdirectory 379 (such as {@link android.os.Environment#DIRECTORY_MOVIES}). If you don't need a specific 380 media directory, pass <code>null</code> to receive 381 the root directory of your app's private directory.</p> 382 383 <p>Beginning with Android 4.4, reading or writing files in your app's private 384 directories does not require the {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} 385 or {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} 386 permissions. So you can declare the permission should be requested only on the lower versions 387 of Android by adding the <a 388 href="{@docRoot}guide/topics/manifest/uses-permission-element.html#maxSdk">{@code maxSdkVersion}</a> 389 attribute:</p> 390 <pre> 391 <manifest ...> 392 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 393 android:maxSdkVersion="18" /> 394 ... 395 </manifest> 396 </pre> 397 398 <p class="note"><strong>Note:</strong> 399 When the user uninstalls your application, this directory and all its contents are deleted. 400 Also, the system media scanner does not read files in these directories, so they are not accessible 401 from the {@link android.provider.MediaStore} content provider. As such, you <b>should not 402 use these directories</b> for media that ultimately belongs to the user, such as photos 403 captured or edited with your app, or music the user has purchased with your app—those 404 files should be <a href="#SavingSharedFiles">saved in the public directories</a>.</p> 405 406 <p>Sometimes, a device that has allocated a partition of the 407 internal memory for use as the external storage may also offer an SD card slot. 408 When such a device is running Android 4.3 and lower, the {@link 409 android.content.Context#getExternalFilesDir(String) getExternalFilesDir()} method provides 410 access to only the internal partition and your app cannot read or write to the SD card. 411 Beginning with Android 4.4, however, you can access both locations by calling 412 {@link android.content.Context#getExternalFilesDirs getExternalFilesDirs()}, 413 which returns a {@link 414 java.io.File} array with entries each location. The first entry in the array is considered 415 the primary external storage and you should use that location unless it's full or 416 unavailable. If you'd like to access both possible locations while also supporting Android 417 4.3 and lower, use the <a href="{@docRoot}tools/support-library/index.html">support library's</a> 418 static method, {@link android.support.v4.content.ContextCompat#getExternalFilesDirs 419 ContextCompat.getExternalFilesDirs()}. This also returns a {@link 420 java.io.File} array, but always includes only one entry on Android 4.3 and lower.</p> 421 422 <p class="caution"><strong>Caution</strong> Although the directories provided by {@link 423 android.content.Context#getExternalFilesDir(String) getExternalFilesDir()} and {@link 424 android.content.Context#getExternalFilesDirs getExternalFilesDirs()} are not accessible by the 425 {@link android.provider.MediaStore} content provider, other apps with the {@link 426 android.Manifest.permission#READ_EXTERNAL_STORAGE} permission can access all files on the external 427 storage, including these. If you need to completely restrict access for your files, you should 428 instead write your files to the <a href="#filesInternal">internal storage</a>.</p> 429 430 431 432 433 434 <h3 id="ExternalCache">Saving cache files</h3> 435 436 <p>To open a {@link java.io.File} that represents the 437 external storage directory where you should save cache files, call {@link 438 android.content.Context#getExternalCacheDir()}. If the user uninstalls your 439 application, these files will be automatically deleted.</p> 440 441 <p>Similar to {@link android.support.v4.content.ContextCompat#getExternalFilesDirs 442 ContextCompat.getExternalFilesDirs()}, mentioned above, you can also access a cache directory on 443 a secondary external storage (if available) by calling 444 {@link android.support.v4.content.ContextCompat#getExternalCacheDirs 445 ContextCompat.getExternalCacheDirs()}.</p> 446 447 <p class="note"><strong>Tip:</strong> 448 To preserve file space and maintain your app's performance, 449 it's important that you carefully manage your cache files and remove those that aren't 450 needed anymore throughout your app's lifecycle.</p> 451 452 453 454 455 <h2 id="db">Using Databases</h2> 456 457 <p>Android provides full support for <a href="http://www.sqlite.org/">SQLite</a> databases. 458 Any databases you create will be accessible by name to any 459 class in the application, but not outside the application.</p> 460 461 <p>The recommended method to create a new SQLite database is to create a subclass of {@link 462 android.database.sqlite.SQLiteOpenHelper} and override the {@link 463 android.database.sqlite.SQLiteOpenHelper#onCreate(SQLiteDatabase) onCreate()} method, in which you 464 can execute a SQLite command to create tables in the database. For example:</p> 465 466 <pre> 467 public class DictionaryOpenHelper extends SQLiteOpenHelper { 468 469 private static final int DATABASE_VERSION = 2; 470 private static final String DICTIONARY_TABLE_NAME = "dictionary"; 471 private static final String DICTIONARY_TABLE_CREATE = 472 "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" + 473 KEY_WORD + " TEXT, " + 474 KEY_DEFINITION + " TEXT);"; 475 476 DictionaryOpenHelper(Context context) { 477 super(context, DATABASE_NAME, null, DATABASE_VERSION); 478 } 479 480 @Override 481 public void onCreate(SQLiteDatabase db) { 482 db.execSQL(DICTIONARY_TABLE_CREATE); 483 } 484 } 485 </pre> 486 487 <p>You can then get an instance of your {@link android.database.sqlite.SQLiteOpenHelper} 488 implementation using the constructor you've defined. To write to and read from the database, call 489 {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase()} and {@link 490 android.database.sqlite.SQLiteOpenHelper#getReadableDatabase()}, respectively. These both return a 491 {@link android.database.sqlite.SQLiteDatabase} object that represents the database and 492 provides methods for SQLite operations.</p> 493 494 <div class="sidebox-wrapper"> 495 <div class="sidebox"> 496 <p>Android does not impose any limitations beyond the standard SQLite concepts. We do recommend 497 including an autoincrement value key field that can be used as a unique ID to 498 quickly find a record. This is not required for private data, but if you 499 implement a <a href="{@docRoot}guide/topics/providers/content-providers.html">content provider</a>, 500 you must include a unique ID using the {@link android.provider.BaseColumns#_ID BaseColumns._ID} 501 constant. 502 </p> 503 </div> 504 </div> 505 506 <p>You can execute SQLite queries using the {@link android.database.sqlite.SQLiteDatabase} 507 {@link 508 android.database.sqlite.SQLiteDatabase#query(boolean,String,String[],String,String[],String,String,String,String) 509 query()} methods, which accept various query parameters, such as the table to query, 510 the projection, selection, columns, grouping, and others. For complex queries, such as 511 those that require column aliases, you should use 512 {@link android.database.sqlite.SQLiteQueryBuilder}, which provides 513 several convienent methods for building queries.</p> 514 515 <p>Every SQLite query will return a {@link android.database.Cursor} that points to all the rows 516 found by the query. The {@link android.database.Cursor} is always the mechanism with which 517 you can navigate results from a database query and read rows and columns.</p> 518 519 <p>For sample apps that demonstrate how to use SQLite databases in Android, see the 520 <a href="{@docRoot}resources/samples/NotePad/index.html">Note Pad</a> and 521 <a href="{@docRoot}resources/samples/SearchableDictionary/index.html">Searchable Dictionary</a> 522 applications.</p> 523 524 525 <h3 id="dbDebugging">Database debugging</h3> 526 527 <p>The Android SDK includes a {@code sqlite3} database tool that allows you to browse 528 table contents, run SQL commands, and perform other useful functions on SQLite 529 databases. See <a href="{@docRoot}tools/help/adb.html#sqlite">Examining sqlite3 530 databases from a remote shell</a> to learn how to run this tool. 531 </p> 532 533 534 535 536 537 <h2 id="netw">Using a Network Connection</h2> 538 539 <!-- TODO MAKE THIS USEFUL!! --> 540 541 <p>You can use the network (when it's available) to store and retrieve data on your own web-based 542 services. To do network operations, use classes in the following packages:</p> 543 544 <ul class="no-style"> 545 <li><code>{@link java.net java.net.*}</code></li> 546 <li><code>{@link android.net android.net.*}</code></li> 547 </ul> 548