• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Storage Options
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&mdash; 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    &#64;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    &#64;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>&lt;filename&gt;</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>It's possible that a device using a partition of the
236internal storage for the external storage may also offer an SD card slot. In this case,
237the SD card is <em>not</em> part of the external storage and your app cannot access it (the extra
238storage is intended only for user-provided media that the system scans).</p>
239
240<p class="caution"><strong>Caution:</strong> External storage can become unavailable if the user mounts the
241external storage on a computer or removes the media, and there's no security enforced upon files you
242save to the external storage. All applications can read and write files placed on the external
243storage and the user can remove them.</p>
244
245
246<h3 id="MediaAvail">Checking media availability</h3>
247
248<p>Before you do any work with the external storage, you should always call {@link
249android.os.Environment#getExternalStorageState()} to check whether the media is available. The
250media might be mounted to a computer, missing, read-only, or in some other state. For example,
251here's how you can check the availability:</p>
252
253<pre>
254boolean mExternalStorageAvailable = false;
255boolean mExternalStorageWriteable = false;
256String state = Environment.getExternalStorageState();
257
258if (Environment.MEDIA_MOUNTED.equals(state)) {
259    // We can read and write the media
260    mExternalStorageAvailable = mExternalStorageWriteable = true;
261} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
262    // We can only read the media
263    mExternalStorageAvailable = true;
264    mExternalStorageWriteable = false;
265} else {
266    // Something else is wrong. It may be one of many other states, but all we need
267    //  to know is we can neither read nor write
268    mExternalStorageAvailable = mExternalStorageWriteable = false;
269}
270</pre>
271
272<p>This example checks whether the external storage is available to read and write. The
273{@link android.os.Environment#getExternalStorageState()} method returns other states that you
274might want to check, such as whether the media is being shared (connected to a computer), is missing
275entirely, has been removed badly, etc. You can use these to notify the user with more information
276when your application needs to access the media.</p>
277
278
279<h3 id="AccessingExtFiles">Accessing files on external storage</h3>
280
281<p>If you're using API Level 8 or greater, use {@link
282android.content.Context#getExternalFilesDir(String) getExternalFilesDir()} to open a {@link
283java.io.File} that represents the external storage directory where you should save your
284files. This method takes a <code>type</code> parameter that specifies the type of subdirectory you
285want, such as {@link android.os.Environment#DIRECTORY_MUSIC} and
286{@link android.os.Environment#DIRECTORY_RINGTONES} (pass <code>null</code> to receive
287the root of your application's file directory). This method will create the
288appropriate directory if necessary. By specifying the type of directory, you
289ensure that the Android's media scanner will properly categorize your files in the system (for
290example, ringtones are identified as ringtones and not music). If the user uninstalls your
291application, this directory and all its contents will be deleted.</p>
292
293<p>If you're using API Level 7 or lower, use {@link
294android.os.Environment#getExternalStorageDirectory()}, to open a {@link
295java.io.File} representing the root of the external storage. You should then write your data in the
296following directory:</p>
297<pre class="no-pretty-print classic">
298/Android/data/<em>&lt;package_name&gt;</em>/files/
299</pre>
300<p>The {@code <em>&lt;package_name&gt;</em>} is your Java-style package name, such as "{@code
301com.example.android.app}". If the user's device is running API Level 8 or greater and they
302uninstall your application, this directory and all its contents will be deleted.</p>
303
304
305<div class="sidebox-wrapper" style="margin-top:3em">
306<div class="sidebox">
307
308<h4>Hiding your files from the Media Scanner</h4>
309
310<p>Include an empty file named {@code .nomedia} in your external files directory (note the dot
311prefix in the filename). This will prevent Android's media scanner from reading your media
312files and including them in apps like Gallery or Music.</p>
313
314</div>
315</div>
316
317
318<h3 id="SavingSharedFiles">Saving files that should be shared</h3>
319
320<p>If you want to save files that are not specific to your application and that should <em>not</em>
321be deleted when your application is uninstalled, save them to one of the public directories on the
322external storage. These directories lay at the root of the external storage, such as {@code
323Music/}, {@code Pictures/}, {@code Ringtones/}, and others.</p>
324
325<p>In API Level 8 or greater, use {@link
326android.os.Environment#getExternalStoragePublicDirectory(String)
327getExternalStoragePublicDirectory()}, passing it the type of public directory you want, such as
328{@link android.os.Environment#DIRECTORY_MUSIC}, {@link android.os.Environment#DIRECTORY_PICTURES},
329{@link android.os.Environment#DIRECTORY_RINGTONES}, or others. This method will create the
330appropriate directory if necessary.</p>
331
332<p>If you're using API Level 7 or lower, use {@link
333android.os.Environment#getExternalStorageDirectory()} to open a {@link java.io.File} that represents
334the root of the external storage, then save your shared files in one of the following
335directories:</p>
336
337<ul class="nolist"></li>
338  <li><code>Music/</code> - Media scanner classifies all media found here as user music.</li>
339  <li><code>Podcasts/</code> - Media scanner classifies all media found here as a podcast.</li>
340  <li><code>Ringtones/ </code> - Media scanner classifies all media found here as a ringtone.</li>
341  <li><code>Alarms/</code> - Media scanner classifies all media found here as an alarm sound.</li>
342  <li><code>Notifications/</code> - Media scanner classifies all media found here as a notification
343sound.</li>
344  <li><code>Pictures/</code> - All photos (excluding those taken with the camera).</li>
345  <li><code>Movies/</code> - All movies (excluding those taken with the camcorder).</li>
346  <li><code>Download/</code> - Miscellaneous downloads.</li>
347</ul>
348
349
350<h3 id="ExternalCache">Saving cache files</h3>
351
352<p>If you're using API Level 8 or greater, use {@link
353android.content.Context#getExternalCacheDir()} to open a {@link java.io.File} that represents the
354external storage directory where you should save cache files. If the user uninstalls your
355application, these files will be automatically deleted. However, during the life of your
356application, you should manage these cache files and remove those that aren't needed in order to
357preserve file space.</p>
358
359<p>If you're using API Level 7 or lower, use {@link
360android.os.Environment#getExternalStorageDirectory()} to open a {@link java.io.File} that represents
361the root of the external storage, then write your cache data in the following directory:</p>
362<pre class="no-pretty-print classic">
363/Android/data/<em>&lt;package_name&gt;</em>/cache/
364</pre>
365<p>The {@code <em>&lt;package_name&gt;</em>} is your Java-style package name, such as "{@code
366com.example.android.app}".</p>
367
368
369
370<h2 id="db">Using Databases</h2>
371
372<p>Android provides full support for <a href="http://www.sqlite.org/">SQLite</a> databases.
373Any databases you create will be accessible by name to any
374class in the application, but not outside the application.</p>
375
376<p>The recommended method to create a new SQLite database is to create a subclass of {@link
377android.database.sqlite.SQLiteOpenHelper} and override the {@link
378android.database.sqlite.SQLiteOpenHelper#onCreate(SQLiteDatabase) onCreate()} method, in which you
379can execute a SQLite command to create tables in the database. For example:</p>
380
381<pre>
382public class DictionaryOpenHelper extends SQLiteOpenHelper {
383
384    private static final int DATABASE_VERSION = 2;
385    private static final String DICTIONARY_TABLE_NAME = "dictionary";
386    private static final String DICTIONARY_TABLE_CREATE =
387                "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
388                KEY_WORD + " TEXT, " +
389                KEY_DEFINITION + " TEXT);";
390
391    DictionaryOpenHelper(Context context) {
392        super(context, DATABASE_NAME, null, DATABASE_VERSION);
393    }
394
395    &#64;Override
396    public void onCreate(SQLiteDatabase db) {
397        db.execSQL(DICTIONARY_TABLE_CREATE);
398    }
399}
400</pre>
401
402<p>You can then get an instance of your {@link android.database.sqlite.SQLiteOpenHelper}
403implementation using the constructor you've defined. To write to and read from the database, call
404{@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase()} and {@link
405android.database.sqlite.SQLiteOpenHelper#getReadableDatabase()}, respectively. These both return a
406{@link android.database.sqlite.SQLiteDatabase} object that represents the database and
407provides methods for SQLite operations.</p>
408
409<div class="sidebox-wrapper">
410<div class="sidebox">
411<p>Android does not impose any limitations beyond the standard SQLite concepts. We do recommend
412including an autoincrement value key field that can be used as a unique ID to
413quickly find a record.  This is not required for private data, but if you
414implement a <a href="{@docRoot}guide/topics/providers/content-providers.html">content provider</a>,
415you must include a unique ID using the {@link android.provider.BaseColumns#_ID BaseColumns._ID}
416constant.
417</p>
418</div>
419</div>
420
421<p>You can execute SQLite queries using the {@link android.database.sqlite.SQLiteDatabase}
422{@link
423android.database.sqlite.SQLiteDatabase#query(boolean,String,String[],String,String[],String,String,String,String)
424query()} methods, which accept various query parameters, such as the table to query,
425the projection, selection, columns, grouping, and others. For complex queries, such as
426those that require column aliases, you should use
427{@link android.database.sqlite.SQLiteQueryBuilder}, which provides
428several convienent methods for building queries.</p>
429
430<p>Every SQLite query will return a {@link android.database.Cursor} that points to all the rows
431found by the query. The {@link android.database.Cursor} is always the mechanism with which
432you can navigate results from a database query and read rows and columns.</p>
433
434<p>For sample apps that demonstrate how to use SQLite databases in Android, see the
435<a href="{@docRoot}resources/samples/NotePad/index.html">Note Pad</a> and
436<a href="{@docRoot}resources/samples/SearchableDictionary/index.html">Searchable Dictionary</a>
437applications.</p>
438
439
440<h3 id="dbDebugging">Database debugging</h3>
441
442<p>The Android SDK includes a {@code sqlite3} database tool that allows you to browse
443table contents, run SQL commands, and perform other useful functions on SQLite
444databases.  See <a href="{@docRoot}tools/help/adb.html#sqlite">Examining sqlite3
445databases from a remote shell</a> to learn how to run this tool.
446</p>
447
448
449
450
451
452<h2 id="netw">Using a Network Connection</h2>
453
454<!-- TODO MAKE THIS USEFUL!! -->
455
456<p>You can use the network (when it's available) to store and retrieve data on your own web-based
457services. To do network operations, use classes in the following packages:</p>
458
459<ul class="no-style">
460  <li><code>{@link java.net java.net.*}</code></li>
461  <li><code>{@link android.net android.net.*}</code></li>
462</ul>
463