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