Data Storage
Android provides several options for youto save persistent application data. The solution you choose depends on yourspecific needs, such as whether the data should be private to your applicationor accessible to other applications (and the user) and how much space your datarequires.
Your data storage options are thefollowing:
Store private primitive data in key-value pairs.
Store private data on the device memory.
Store public data on the shared external storage.
Store structured data in a private database.
Store data on the web with your own network server.
Android provides a way for you to exposeeven your private data to other applications — with a content provider. Acontent provider is an optional component that exposes read/write access toyour application data, subject to whatever restrictions you want to impose. Formore information about using content providers, see the Content Providers documentation.
Using SharedPreferences
The SharedPreferences
class provides a general framework that allows you to saveand retrieve persistent key-value pairs of primitive data types. You can useSharedPreferences
to save any primitive data: booleans, floats, ints, longs,and strings. This data will persist across user sessions (even if yourapplication is killed).
To get a SharedPreferences object for your application, use one oftwo methods:
· getSharedPreferences() - Use this if you need multiplepreferences files identified by name, which you specify with the firstparameter.
· getPreferences() - Use this if you need only onepreferences file for your Activity. Because this will be the only preferencesfile for your Activity, you don't supply a name.
To write values:
1. Call edit() to get a SharedPreferences.Editor.
2. Add values with methods such as putBoolean() and putString().
3. Commit the new values with commit()
To read values, use SharedPreferences methods such as getBoolean() and getString().
Here is an example that saves apreference for silent keypress mode in a calculator:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings =getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
User Preferences
Shared preferences are not strictly forsaving "user preferences," such as what ringtone a user has chosen.If you're interested in creating user preferences for your application, seePreferenceActivity
, which provides an Activity framework for you to createuser preferences, which will be automatically persisted (using sharedpreferences).
Using the InternalStorage
You can save filesdirectly on the device's internal storage. By default, files saved to theinternal storage are private to your application and other applications cannotaccess them (nor can the user). When the user uninstalls your application,these files are removed.
To create and write aprivate file to the internal storage:
1. Call openFileOutput()
with the name of the file and the operating mode. Thisreturns a FileOutputStream
.
2. Write to thefile with write()
.
3. Close thestream with close()
.
For example:
String FILENAME = "hello_file"; String string = "hello world!"; FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close();
MODE_PRIVATE
will create the file (or replace a file of the same name) andmake it private to your application. Other modes available are: MODE_APPEND
,MODE_WORLD_READABLE
, and MODE_WORLD_WRITEABLE
.
To read a file frominternal storage:
1. Call openFileInput()
and pass it the name of the file to read. This returns a FileInputStream
.
2. Read bytesfrom the file with read()
.
3. Then close thestream with close()
.
Tip: If you want tosave a static file in your application at compile time, save the file in yourproject res/raw/
directory. You can open it with openRawResource()
, passing the R.raw.
<filename> resource ID. This method returns an InputStream
that you can use to read the file (but you cannot write tothe original file).
Saving cache files
If you'd like to cachesome data, rather than store it persistently, you should use getCacheDir()
to open a File
that represents the internal directory where your applicationshould save temporary cache files.
When the device is low oninternal storage space, Android may delete these cache files to recover space.However, you should not rely on the system to clean up these files for you. Youshould always maintain the cache files yourself and stay within a reasonablelimit of space consumed, such as 1MB. When the user uninstalls yourapplication, these files are removed.
Other useful methods
Gets theabsolute path to the filesystem directory where your internal files are saved.
Creates (oropens an existing) directory within your internal storage space.
Deletes a filesaved on the internal storage.
Returns anarray of files currently saved by your application.
Using the ExternalStorage
Every Android-compatibledevice supports a shared "external storage" that you can use to savefiles. This can be a removable storage media (such as an SD card) or aninternal (non-removable) storage. Files saved to the external storage areworld-readable and can be modified by the user when they enable USB massstorage to transfer files on a computer.
Caution: External filescan disappear if the user mounts the external storage on a computer or removesthe media, and there's no security enforced upon files you save to the externalstorage. All applications can read and write files placed on the externalstorage and the user can remove them.
Checking mediaavailability
Before you do any workwith the external storage, you should always call getExternalStorageState()
to check whether the media is available. The media might bemounted to a computer, missing, read-only, or in some other state. For example,here's how you can check the availability:
boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; }
This example checkswhether the external storage is available to read and write. The getExternalStorageState()
method returns other states that you might want to check,such as whether the media is being shared (connected to a computer), is missingentirely, has been removed badly, etc. You can use these to notify the userwith more information when your application needs to access the media.
Accessing files onexternal storage
If you're using API Level8 or greater, use getExternalFilesDir()
to open a File
that represents the external storage directory where youshould save your files. This method takes a type
parameter that specifies the type of subdirectory you want,such as DIRECTORY_MUSIC
and DIRECTORY_RINGTONES
(pass null
to receive the root of your application's file directory).This method will create the appropriate directory if necessary. By specifyingthe type of directory, you ensure that the Android's media scanner willproperly categorize your files in the system (for example, ringtones areidentified as ringtones and not music). If the user uninstalls yourapplication, this directory and all its contents will be deleted.
If you're using API Level7 or lower, use getExternalStorageDirectory()
, to open a File
representing the root of the external storage. You shouldthen write your data in the following directory:
/Android/data/<package_name>/files/
The <package_name> is your Java-style package name, such as "com.example.android.app
". If the user's device is running API Level 8 orgreater and they uninstall your application, this directory and all itscontents will be deleted.
Saving files that shouldbe shared
If you want to save filesthat are not specific to your application and that should not be deleted when your application isuninstalled, save them to one of the public directories on the externalstorage. These directories lay at the root of the external storage, such as Music/
, Pictures/
, Ringtones/
, and others.
In API Level 8 or greater,use getExternalStoragePublicDirectory()
, passing it the type of public directory you want, such as DIRECTORY_MUSIC
, DIRECTORY_PICTURES
, DIRECTORY_RINGTONES
, or others. This method will create the appropriatedirectory if necessary.
If you're using API Level7 or lower, use getExternalStorageDirectory()
to open a File
that represents the root of the external storage, then saveyour shared files in one of the following directories:
· Music/
- Media scanner classifies all media found here as usermusic.
· Podcasts/
- Media scanner classifies all media found here as a podcast.
· Ringtones/
- Media scanner classifies all media found here as aringtone.
· Alarms/
- Media scanner classifies all media found here as an alarmsound.
· Notifications/
- Media scanner classifies all media found here as anotification sound.
· Pictures/
- All photos (excluding those taken with the camera).
· Movies/
- All movies (excluding those taken with the camcorder).
· Download/
- Miscellaneous downloads.
Saving cache files
If you're using API Level8 or greater, use getExternalCacheDir()
to open a File
that represents the external storage directory where youshould save cache files. If the user uninstalls your application, these fileswill be automatically deleted. However, during the life of your application,you should manage these cache files and remove those that aren't needed inorder to preserve file space.
If you're using API Level7 or lower, use getExternalStorageDirectory()
to open a File
that represents the root of the external storage, then writeyour cache data in the following directory:
/Android/data/<package_name>/cache/
The <package_name> is your Java-style package name, such as "com.example.android.app
".
Hiding your files from the Media Scanner
Include an empty file named .nomedia
in your external files directory (note the dot prefix inthe filename). This will prevent Android's media scanner from reading yourmedia files and including them in apps like Gallery or Music.
Using Databases
Android provides fullsupport for SQLite databases. Any databases you createwill be accessible by name to any class in the application, but not outside theapplication.
The recommended method tocreate a new SQLite database is to create a subclass of SQLiteOpenHelper
and override the onCreate()
method, in which you can execute a SQLite command to createtables in the database. For example:
public class DictionaryOpenHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 2; private static final String DICTIONARY_TABLE_NAME = "dictionary"; private static final String DICTIONARY_TABLE_CREATE = "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" + KEY_WORD + " TEXT, " + KEY_DEFINITION + " TEXT);"; DictionaryOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DICTIONARY_TABLE_CREATE); } }
You can then get aninstance of your SQLiteOpenHelper
implementation using the constructor you've defined. To writeto and read from the database, callgetWritableDatabase()
and getReadableDatabase()
, respectively. These both return a SQLiteDatabase
object that represents the database and provides methods forSQLite operations.
You can execute SQLitequeries using the SQLiteDatabase
query()
methods, which accept various query parameters, such as thetable to query, the projection, selection, columns, grouping, and others. Forcomplex queries, such as those that require column aliases, you should use SQLiteQueryBuilder
, which provides several convienent methods for buildingqueries.
Every SQLite query willreturn a Cursor
that points to all the rows found by the query. The Cursor
is always the mechanism with which you can navigate resultsfrom a database query and read rows and columns.
For sample apps thatdemonstrate how to use SQLite databases in Android, see the Note Pad andSearchable Dictionary applications.
Database debugging
The Android SDK includes a sqlite3
database tool that allows you to browse table contents, runSQL commands, and perform other useful functions on SQLite databases. See Examining sqlite3 databases from a remote shell to learn how to run this tool.
Android does not impose any limitations beyond the standardSQLite concepts. We do recommend including an autoincrement value key fieldthat can be used as a unique ID to quickly find a record. This is not requiredfor private data, but if you implement a content provider, you must include a unique IDusing the BaseColumns._ID
constant.
Using a NetworkConnection
You can use the network(when it's available) to store and retrieve data on your own web-basedservices. To do network operations, use classes in the following packages: