1page.title=Storage Options 2page.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 35choose depends on your specific needs, such as whether the data should be private to your 36application or accessible to other applications (and the user) and how much space your data 37requires. 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 57provider</a>. A content provider is an optional component that exposes read/write access to 58your application data, subject to whatever restrictions you want to impose. For more information 59about using content providers, see the 60<a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a> 61documentation. 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 70to save and retrieve persistent key-value pairs of primitive data types. You can use {@link 71android.content.SharedPreferences} to save any primitive data: booleans, floats, ints, longs, and 72strings. 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 78user has chosen. If you're interested in creating user preferences for your application, see {@link 79android.preference.PreferenceActivity}, which provides an Activity framework for you to create 80user 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 85two methods:</p> 86<ul> 87 <li>{@link android.content.Context#getSharedPreferences(String,int) 88getSharedPreferences()} - Use this if you need multiple preferences files identified by name, 89which you specify with the first parameter.</li> 90 <li>{@link android.app.Activity#getPreferences(int) getPreferences()} - Use this if you need 91only one preferences file for your Activity. Because this will be the only preferences file 92for 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 98android.content.SharedPreferences.Editor}.</li> 99 <li>Add values with methods such as {@link 100android.content.SharedPreferences.Editor#putBoolean(String,boolean) putBoolean()} and {@link 101android.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 106android.content.SharedPreferences#getBoolean(String,boolean) getBoolean()} and {@link 107android.content.SharedPreferences#getString(String,String) getString()}.</p> 108 109<p> 110Here is an example that saves a preference for silent keypress mode in a 111calculator: 112</p> 113 114<pre> 115public 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 152to the internal storage are private to your application and other applications cannot access 153them (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 159name 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> 167String FILENAME = "hello_file"; 168String string = "hello world!"; 169 170FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 171fos.write(string.getBytes()); 172fos.close(); 173</pre> 174 175<p>{@link android.content.Context#MODE_PRIVATE} will create the file (or replace a file of 176the same name) and make it private to your application. Other modes available are: {@link 177android.content.Context#MODE_APPEND}, {@link 178android.content.Context#MODE_WORLD_READABLE}, and {@link 179android.content.Context#MODE_WORLD_WRITEABLE}.</p> 180 181<p class="note"><strong>Note:</strong> The constants {@link 182android.content.Context#MODE_WORLD_READABLE} and {@link 183android.content.Context#MODE_WORLD_WRITEABLE} have been deprecated since API level 17. 184Starting from Android N their use will result in a {@link java.lang.SecurityException} 185to be thrown. 186This means that apps targeting Android N and higher 187cannot 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 189files with other apps, it may use a {@link android.support.v4.content.FileProvider} with 190the {@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION}. 191See also <a 192href="{@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 199name 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) 201read()}.</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 206compile 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} 209that 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 216android.content.Context#getCacheDir()} to open a {@link 217java.io.File} that represents the internal directory where your application should save 218temporary cache files.</p> 219 220<p>When the device is 221low on internal storage space, Android may delete these cache files to recover space. However, you 222should not rely on the system to clean up these files for you. You should always maintain the cache 223files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user 224uninstalls 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 246save 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 248be 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 251external storage on a computer or removes the media, and there's no security enforced upon files you 252save to the external storage. All applications can read and write files placed on the external 253storage and the user can remove them.</p> 254 255<h3 id="ScopedDirAccess">Using Scoped Directory Access</h3> 256 257On Android 7.0 or later, if you need access to a specific directory on 258external storage, use scoped directory access. Scoped directory access 259simplifies how your application accesses standard external storage directories, 260such as the <code>Pictures</code> directory, and provides a simple 261permissions UI that clearly details what directory the application is 262requesting access to. For more details on scoped directory access, see 263<a href="{@docRoot}training/articles/scoped-directory-access.html">Using 264Scoped 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} 270or {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} system 271permissions. 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 281implicitly requires read access as well.</p> 282 283<p class="note"><strong>Note:</strong> Beginning with Android 4.4, these permissions are not 284required if you're reading or writing only files that are private to your app. For more 285information, 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 293android.os.Environment#getExternalStorageState()} to check whether the media is available. The 294media might be mounted to a computer, missing, read-only, or in some other state. For example, 295here 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 */ 299public 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 */ 308public 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 319might want to check, such as whether the media is being shared (connected to a computer), is missing 320entirely, has been removed badly, etc. You can use these to notify the user with more information 321when 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 332prefix in the filename). This prevents media scanner from reading your media 333files and providing them to other apps through the {@link android.provider.MediaStore} 334content 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" 341location on the device where other apps can access them and the user can easily copy them from the 342device. When doing so, you should use to one of the shared public directories, such as {@code 343Music/}, {@code Pictures/}, and {@code Ringtones/}.</p> 344 345<p>To get a {@link java.io.File} representing the appropriate public directory, call {@link 346android.os.Environment#getExternalStoragePublicDirectory(String) 347getExternalStoragePublicDirectory()}, 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 350corresponding media-type directory, 351the system's media scanner can properly categorize your files in the system (for 352instance, 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 356the public pictures directory:</p> 357 358<pre> 359public 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 376a private storage directory on the external storage by calling {@link 377android.content.Context#getExternalFilesDir(String) getExternalFilesDir()}. 378This 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 380media directory, pass <code>null</code> to receive 381the 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 384directories does not require the {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} 385or {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} 386permissions. So you can declare the permission should be requested only on the lower versions 387of Android by adding the <a 388href="{@docRoot}guide/topics/manifest/uses-permission-element.html#maxSdk">{@code maxSdkVersion}</a> 389attribute:</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> 399When the user uninstalls your application, this directory and all its contents are deleted. 400Also, the system media scanner does not read files in these directories, so they are not accessible 401from the {@link android.provider.MediaStore} content provider. As such, you <b>should not 402use these directories</b> for media that ultimately belongs to the user, such as photos 403captured or edited with your app, or music the user has purchased with your app—those 404files 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 407internal memory for use as the external storage may also offer an SD card slot. 408When such a device is running Android 4.3 and lower, the {@link 409android.content.Context#getExternalFilesDir(String) getExternalFilesDir()} method provides 410access to only the internal partition and your app cannot read or write to the SD card. 411Beginning with Android 4.4, however, you can access both locations by calling 412{@link android.content.Context#getExternalFilesDirs getExternalFilesDirs()}, 413which returns a {@link 414java.io.File} array with entries each location. The first entry in the array is considered 415the primary external storage and you should use that location unless it's full or 416unavailable. If you'd like to access both possible locations while also supporting Android 4174.3 and lower, use the <a href="{@docRoot}tools/support-library/index.html">support library's</a> 418static method, {@link android.support.v4.content.ContextCompat#getExternalFilesDirs 419ContextCompat.getExternalFilesDirs()}. This also returns a {@link 420java.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 423android.content.Context#getExternalFilesDir(String) getExternalFilesDir()} and {@link 424android.content.Context#getExternalFilesDirs getExternalFilesDirs()} are not accessible by the 425{@link android.provider.MediaStore} content provider, other apps with the {@link 426android.Manifest.permission#READ_EXTERNAL_STORAGE} permission can access all files on the external 427storage, including these. If you need to completely restrict access for your files, you should 428instead 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 437external storage directory where you should save cache files, call {@link 438android.content.Context#getExternalCacheDir()}. If the user uninstalls your 439application, these files will be automatically deleted.</p> 440 441<p>Similar to {@link android.support.v4.content.ContextCompat#getExternalFilesDirs 442ContextCompat.getExternalFilesDirs()}, mentioned above, you can also access a cache directory on 443a secondary external storage (if available) by calling 444{@link android.support.v4.content.ContextCompat#getExternalCacheDirs 445ContextCompat.getExternalCacheDirs()}.</p> 446 447<p class="note"><strong>Tip:</strong> 448To preserve file space and maintain your app's performance, 449it's important that you carefully manage your cache files and remove those that aren't 450needed 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. 458Any databases you create will be accessible by name to any 459class 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 462android.database.sqlite.SQLiteOpenHelper} and override the {@link 463android.database.sqlite.SQLiteOpenHelper#onCreate(SQLiteDatabase) onCreate()} method, in which you 464can execute a SQLite command to create tables in the database. For example:</p> 465 466<pre> 467public 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} 488implementation using the constructor you've defined. To write to and read from the database, call 489{@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase()} and {@link 490android.database.sqlite.SQLiteOpenHelper#getReadableDatabase()}, respectively. These both return a 491{@link android.database.sqlite.SQLiteDatabase} object that represents the database and 492provides 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 497including an autoincrement value key field that can be used as a unique ID to 498quickly find a record. This is not required for private data, but if you 499implement a <a href="{@docRoot}guide/topics/providers/content-providers.html">content provider</a>, 500you must include a unique ID using the {@link android.provider.BaseColumns#_ID BaseColumns._ID} 501constant. 502</p> 503</div> 504</div> 505 506<p>You can execute SQLite queries using the {@link android.database.sqlite.SQLiteDatabase} 507{@link 508android.database.sqlite.SQLiteDatabase#query(boolean,String,String[],String,String[],String,String,String,String) 509query()} methods, which accept various query parameters, such as the table to query, 510the projection, selection, columns, grouping, and others. For complex queries, such as 511those that require column aliases, you should use 512{@link android.database.sqlite.SQLiteQueryBuilder}, which provides 513several 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 516found by the query. The {@link android.database.Cursor} is always the mechanism with which 517you 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> 522applications.</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 528table contents, run SQL commands, and perform other useful functions on SQLite 529databases. See <a href="{@docRoot}tools/help/adb.html#sqlite">Examining sqlite3 530databases 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 542services. 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