Android 数据存储

Data Storage

Storage quickview

  • Use Shared Preferences for primitive data
  • Use internal device storage for private data
  • Use external storage for large data sets that are not private
  • Use SQLite databases for structured storage

In this document

  1. Using Shared Preferences
  2. Using the Internal Storage
    1. Saving cache files
    2. Other useful methods
  3. Using the External Storage
    1. Checking media availability
    2. Accessing files on external storage
    3. Saving files that should be shared
    4. Saving cache files
  4. Using Databases
    1. Database debugging
  5. Using a Network Connection

See also

  1. Content Providers and Content Resolvers

Android provides several options for you to save persistent application data. The solution youchoose depends on your specific needs, such as whether the data should be private to yourapplication or accessible to other applications (and the user) and how much space your datarequires.

Your data storage options are the following:

Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server.

Android provides a way for you to expose even your private data to other applications— with a contentprovider. A content provider is an optional component that exposes read/write access toyour application data, subject to whatever restrictions you want to impose. For more informationabout using content providers, see theContent Providersdocumentation.

Using Shared Preferences

The SharedPreferences class provides a general framework that allows youto save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, andstrings. This data will persist across user sessions (even if your application is killed).

To get a SharedPreferences object for your application, use one oftwo methods:

  • getSharedPreferences() - Use this if you need multiple preferences files identified by name,which you specify with the first parameter.
  • getPreferences() - Use this if you needonly one preferences file for your Activity. Because this will be the only preferences filefor 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 a preference for silent keypress mode in acalculator:

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();
    }
}

Using the Internal Storage

You can save files directly on the device's internal storage. By default, files savedto the internal storage are private to your application and other applications cannot accessthem (nor can the user). When the user uninstalls your application, these files are removed.

To create and write a private file to the internal storage:

  1. Call openFileOutput() with thename of the file and the operating mode. This returns a FileOutputStream.
  2. Write to the file with write().
  3. Close the stream 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 ofthe same name) and make it private to your application. Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.

To read a file from internal storage:

  1. Call openFileInput() and pass it thename of the file to read. This returns a FileInputStream.
  2. Read bytes from the file with read().
  3. Then close the stream with close().

Tip: If you want to save a static file in your application atcompile time, save the file in your project res/raw/ directory. You can open it withopenRawResource(), passing the R.raw.<filename> resource ID. This method returns an InputStreamthat you can use to read the file (but you cannot write to the original file).

Saving cache files

If you'd like to cache some data, rather than store it persistently, you should use getCacheDir() to open a File that represents the internal directory where your application should savetemporary cache files.

When the device islow on internal storage space, Android may delete these cache files to recover space. However, youshould not rely on the system to clean up these files for you. You should always maintain the cachefiles yourself and stay within a reasonable limit of space consumed, such as 1MB. When the useruninstalls your application, these files are removed.

Other useful methods

getFilesDir()
Gets the absolute path to the filesystem directory where your internal files are saved.
getDir()
Creates (or opens an existing) directory within your internal storage space.
deleteFile()
Deletes a file saved on the internal storage.
fileList()
Returns an array of files currently saved by your application.

Using the External Storage

Every Android-compatible device supports a shared "external storage" that you can use tosave files. This can be a removable storage media (such as an SD card) or an internal(non-removable) storage. Files saved to the external storage are world-readable and canbe modified by the user when they enable USB mass storage to transfer files on a computer.

Caution: External files can disappear if the user mounts theexternal storage on a computer or removes the media, and there's no security enforced upon files yousave to the external storage. All applications can read and write files placed on the externalstorage and the user can remove them.

Checking media availability

Before you do any work with the external storage, you should always call getExternalStorageState() to check whether the media is available. Themedia might be mounted 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 checks whether the external storage is available to read and write. ThegetExternalStorageState() method returns other states that youmight 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 user with more informationwhen your application needs to access the media.

Accessing files on external storage

If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save yourfiles. This method takes a type parameter that specifies the type of subdirectory youwant, such as DIRECTORY_MUSIC andDIRECTORY_RINGTONES (pass null to receivethe root of your application's file directory). This method will create theappropriate directory if necessary. By specifying the type of directory, youensure that the Android's media scanner will properly categorize your files in the system (forexample, ringtones are identified as ringtones and not music). If the user uninstalls yourapplication, this directory and all its contents will be deleted.

If you're using API Level 7 or lower, use getExternalStorageDirectory(), to open a File representing the root of the external storage. You should then write your data in thefollowing 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 or greater and theyuninstall your application, this directory and all its contents will be deleted.

Saving files that should be shared

If you want to save files that are not specific to your application and that should notbe deleted when your application is uninstalled, save them to one of the public directories on theexternal storage. 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 asDIRECTORY_MUSIC, DIRECTORY_PICTURES,DIRECTORY_RINGTONES, or others. This method will create theappropriate directory if necessary.

If you're using API Level 7 or lower, use getExternalStorageDirectory() to open a File that representsthe root of the external storage, then save your shared files in one of the followingdirectories:

  • Music/ - Media scanner classifies all media found here as user music.
  • Podcasts/ - Media scanner classifies all media found here as a podcast.
  • Ringtones/ - Media scanner classifies all media found here as a ringtone.
  • Alarms/ - Media scanner classifies all media found here as an alarm sound.
  • Notifications/ - Media scanner classifies all media found here as a notificationsound.
  • 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 Level 8 or greater, use getExternalCacheDir() to open a File that represents theexternal storage directory where you should save cache files. If the user uninstalls yourapplication, these files will be automatically deleted. However, during the life of yourapplication, you should manage these cache files and remove those that aren't needed in order topreserve file space.

If you're using API Level 7 or lower, use getExternalStorageDirectory() to open a File that representsthe root of the external storage, then write your 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".

Using Databases

Android provides full support for SQLite databases.Any databases you create will be accessible by name to anyclass in the application, but not outside the application.

The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which youcan execute a SQLite command to create tables 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 an instance of your SQLiteOpenHelperimplementation using the constructor you've defined. To write to and read from the database, callgetWritableDatabase() and getReadableDatabase(), respectively. These both return aSQLiteDatabase object that represents the database andprovides methods for SQLite operations.

You can execute SQLite queries using the SQLiteDatabasequery() methods, which accept various query parameters, such as the table to query,the projection, selection, columns, grouping, and others. For complex queries, such asthose that require column aliases, you should useSQLiteQueryBuilder, which providesseveral convienent methods for building queries.

Every SQLite query will return a Cursor that points to all the rowsfound by the query. The Cursor is always the mechanism with whichyou can navigate results from a database query and read rows and columns.

For sample apps that demonstrate how to use SQLite databases in Android, see theNote Pad andSearchable Dictionaryapplications.

Database debugging

The Android SDK includes a sqlite3 database tool that allows you to browsetable contents, run SQL commands, and perform other useful functions on SQLitedatabases. See Examining sqlite3databases from a remote shell to learn how to run this tool.

Using a Network Connection

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:

  • java.net.*
  • android.net.*

你可能感兴趣的:(android,sqlite,application,database,Dictionary,Primitive)