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