Android Development-API Guide-data storage

Source: Internet
Author: User
Tags sqlite query unique id

Storage Options

English Original: http://developer.android.com/guide/topics/data/data-storage.html
Acquisition Date: 2015-02-06

Overview of storage methods
    • Shared Preference for simple data
    • Internal storage for private data
    • External storage for large-scale public data
    • SQLite Database for structured data
In this article
    1. Using the Shared Preference
    2. Using internal storage
    3. Using external storage
    4. Working with databases
    5. Use a network connection
See
    1. Content Provider and Content Resolver

Android offers a variety of options for persistent data retention. Choose how you want to store it, such as whether the data is private to the application or available to other applications (users), how much storage space is needed, and so on.

Data storage scenarios include the following:

Shared Preferences
Saves the private simple (primitive) type data as a key-value pair (Key-value pairs).
Internal storage
Store private data in the internal storage of the device.
External storage
Public data is saved in the public external storage.
SQLite Database
Save structured data in a private database.
Network connection
storing data on your own WEB server

If you need to expose private data to other applications, Android provides a way to--content Provider. Content Provider can freely set read/write permissions based on limited access to the data. For more information about content Provider, see the documentation for the content Providers.

Using the Shared Preferences

SharedPreferencesclass provides a means of storing and reading simple types of data in a key-value pair. SharedPreferencesyou can save data for any simple type: boolean, float, int, long, and string. This data is persisted and can span user sessions (even if the application is killed).

User Configuration

The Shared preferences is not entirely used to save user preferences, such as a custom ringtone. If you want to create your own user configuration for your application, see PreferenceActivity , this class provides a set of Activity that can be used to create user configurations and is automatically saved as persistent data (via Shared Preferences).

SharedPreferencesThere are two ways to get an object:

    • getSharedPreferences()-If you need to use more than one configuration file, use this method, the first parameter specifies the name of the file.
    • getPreferences()-Use this method if you only need to define a configuration file for the Activity. Because the file is unique to the Activity, it does not need to be named.

Write Data:

    1. Call to edit() get one SharedPreferences.Editor .
    2. putBoolean() putString() Add data using methods and the like.
    3. Use to commit() submit new data.

Reading data is done by means of SharedPreferences getBoolean() and the getString() like.

Here is an example of saving a calculator's mute mode as a configuration file:

1 publicclasscalcextendsactivity{2Publicstaticfinalstring prefs_name = "Myprefsfile";3 4 @Override5 protectedvoid onCreate (Bundle state) {6        Super. OnCreate (state);7        ...8 9        //Restore ConfigurationTenSharedpreferences settings = getsharedpreferences (prefs_name,0); One        BooleanSilent = Settings.getboolean ("Silentmode",false); A setsilent (silent); -     } -  the @Override - protectedvoid onStop () { -        Super. OnStop (); -  +       //an Editor object is required to modify the configuration.  -       //all objects are from Android.context.Context +Sharedpreferences settings = getsharedpreferences (prefs_name,0); ASharedpreferences.editor Editor =Settings.edit (); atEditor.putboolean ("Silentmode", Msilentmode); -  -       //Submit Changes - editor.commit (); -     } -}

Using internal storage

Files can be stored directly in the internal storage. By default, files saved in internal storage are private data for the application, and other applications are inaccessible (nor can other users). When the user uninstalls the app, the files will be deleted.

Follow these steps to create and write a private file in internal storage:

    1. Called openFileOutput() , the parameter is the file name and operation mode. The return value is an FileOutputStream object.
    2. To write() write to the file.
    3. With the close() close stream.

Example:

 1  String FILENAME = "Hello_file" ;  2  stringstring= "Hello world!"  3   Openfileoutput (filename,context.mode_private);  5  fos.write (String.getbytes ());  6  fos.close (); 

MODE_PRIVATEThe schema creates a file (or replaces a file with the same name) and makes it private data for the application. Other available modes are: MODE_APPEND , MODE_WORLD_READABLE , MODE_WORLD_WRITEABLE .

To read a file from the internal store:

    1. Called openFileInput() , the parameter is the name of the file to read. The return value is an FileInputStream object.
    2. Use to read() read several bytes from the file.
    3. With the close() close stream.

Tip: If you need to save the static file at compile time, please store it in the project res/raw/ directory. You can openRawResource() open these files with R.raw.<filename> the resource ID of the parameter. The return value is an InputStream object that can be used to read the file (but cannot write data in the original file).

Save cache file

If some data does not need to be persisted, but only temporarily cached, use the getCacheDir() open one File , which is the internal directory where the application saves the temporary files.

If your device has insufficient internal storage space, Android may delete these cache files to free up space. However, please do not rely on the system to clean up these temporary files. Instead, you should manage your cache files so that they occupy only the necessary space, such as 1MB. These files will be deleted when the user uninstalls the app.

Other common methods
getFilesDir()
Gets the absolute path of the internal file
getDir()
Create (or open an existing) directory in internal storage.
deleteFile()
Delete the files in the internal store.
fileList()
returns an array of file lists that have been saved by the app.
Using external storage

All Android devices support shared "External storage" that can be used to save files. This can be either an unloaded storage medium (such as an SD card) or a built-in (non-unmounted) storage. Files saved on external storage are globally readable (world-readable) and can be modified when USB storage mode (USB mass storage) is enabled and the computer is transferring files.

Warning: When a user hooks an external store to a computer, or the media is unloaded, the external storage becomes unavailable and no security measures can be imposed on the externally stored file. All applications can read and write files from external storage, and users can delete them at any time.

Gain access to external storage

Read and write external storage must be requested READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permissions. For example:

< ... >    < Uses-permissionandroid:name = "Android.permission.WRITE_EXTERNAL_STORAGE" />     ... </ Manifest >

If you want to read and write to the file, simply request WRITE_EXTERNAL_STORAGE permissions, because it also implies a Read permission request.

Note: starting with Android 4.4, if you only read and write files that are private to the application, you no longer need to request these permissions. For more information, see the following sections to save your application's private files.

Check the availability of storage media

Be sure getExternalStorageState() to call to check the availability of the media before using external storage. The storage media may be attached to the computer, removed, read-only, or otherwise. The following are two examples of methods that you can use to check the availability of a media:

1 /*Check if external storage is readable or writable*/2 Publicboolean isexternalstoragewritable () {3String State =environment.getexternalstoragestate ();4     if(Environment.MEDIA_MOUNTED.equals (state)) {5 returntrue;6     }7 Returnfalse;8 }9 Ten /*Check if the external storage is at least readable*/ One Publicboolean isexternalstoragereadable () { AString State =environment.getexternalstoragestate (); -     if(Environment.MEDIA_MOUNTED.equals (state) | | - Environment.MEDIA_MOUNTED_READ_ONLY.equals (state)) { the returntrue; -     } - Returnfalse; -}

getExternalStorageState()The status returned by the method also includes other types, such as whether it is shared (connected to the computer), removed, uninstalled, and so on. When an application needs to access storage media, these states can be used to inform the user of the details.

Save shareable files to Media Scanner hidden files

The file directory that is stored externally contains an .nomedia empty file named (note the file name with ".") Start). This prevents the multimedia file scanner (media Scanner) from reading or MediaStore providing files in that directory to other applications. Of course, if these files are really confined to an app's own use, it should be saved to a private directory.

Typically, a user-created file should be in the "public" area of the device, which is an area that other applications can access, and it is easy for users to copy the files from the device. You can use a common directory, such as Music/ , Pictures/ or Ringtones/ .

getExternalStoragePublicDirectory()a call can get a public directory that represents the File type of directory, such as,,, and DIRECTORY_MUSIC DIRECTORY_PICTURES DIRECTORY_RINGTONES so on. As long as the files are saved to the appropriate directory, the system's Media Scanner can correctly categorize them (for example, the ringtone file will appear in the system-set ringtone list and will not be considered a music file).

For example, the following is a sample of creating a new album directory in a Public picture directory:

1 publicfile Getalbumstoragedir (String albumname) {2     //get the user's public picture directory3File File =NewFile (Environment.getexternalstoragepublicdirectory (4 environment.directory_pictures), albumname);5     if(!File.mkdirs ()) {6LOG.E (Log_tag, "Directory not created");7     }8     returnfile;9}

Save application-Private files

If the file is not intended for use by other applications (such as graphic textures or sound files that are used only by this app), use the private storage directory in the external store to invoke it getExternalFilesDir() . The method also has a type parameter (such as) that specifies the directory type DIRECTORY_MOVIES . If the directory does not need to specify a multimedia type, the pass- null through is returned to the root directory of the application's private directory.

Starting with Android 4.4, applications READ_EXTERNAL_STORAGE or permissions are no longer required for the read-write application Private directory WRITE_EXTERNAL_STORAGE . You can therefore declare both permission requests only when you are in the low version of Android, which is achieved by adding maxSdkVersion properties:

 <  manifest  ...    >  <  uses-permissionandroid:name  = "Android.permission.WRITE_EXTERNAL_STORAGE"   Android:maxsdkversion  = " />   ...  </ manifest  >  

Note: When the user uninstalls the application, the private directory and its contents are deleted. Files in this directory are not read by the system's Media Scanner and are not accessed by Content Provider MediaStore . Therefore, do not store users ' multimedia files in a private directory, such as photos taken or edited through the app, music purchased through the app, etc., which should be saved to a public directory.

Sometimes, some devices request an internal storage area to be used as an external storage and are treated as an SD card. If the device is running Android 4.3 and below, the getExternalFilesDir() method will only access partitions on the internal storage, and the application will not be able to read and write the SD card. However, starting with Android 4.4, both getExternalFilesDirs() blocks can be accessed, and an array containing two pieces of stored content is returned File . The first member of the array is the file in the external store, which should generally be used as long as the space is sufficient and available. If you want to be able to access both regions in the following versions of Android 4.3, use the static method of the support library ContextCompat.getExternalFilesDirs() . It will also return an File array, but only one member will be included in this result array when Android 4.3 is in the following version.

Warning: Although the getExternalFilesDir() directories that are and getExternalFilesDirs() get are not accessible by Content Provider MediaStore , READ_EXTERNAL_STORAGE Other apps that have permissions can access all the files in the external store, including these two directories, of course. If you need full control over the access to the file, write the file to internal storage.

Save cache file

Called getExternalCacheDir() to open the external storage directory where the cache file is stored File . These files are automatically deleted when the user uninstalls the application.

Similar to the above ContextCompat.getExternalFilesDirs() , you can ContextCompat.getExternalCacheDirs() access the cache directory in both external storage (if available).

tip: in order to save space and maintain program performance, the cache files should be well managed and deleted in a timely manner during the entire lifecycle of the application.

Working with databases

Android implements full support for the database of the SQLite database. All classes in the application can access the database created by the app by name, but other applications cannot.

Recommended by NewSQLiteOpenHelper/code> 的一个子类来创建 SQLite 数据库。请覆盖其 onCreate() 方法,以便执行建立数据表的 SQLite 命令。例如:

1Publicn>classdictionaryopenhelperextendssqliteopenhelper{2 3Privatestaticfinalint database_version =2;4Privatestaticfinalstring dictionary_table_name = "DICTIONARY";5Privatestaticfinalstring dictionary_table_create =6"CREATE TABLE" + Dictionary_table_name + "(" +7Key_word + "TEXT," +8Key_definition + "TEXT);";9 Ten Dictionaryopenhelper (Context context) { One         Super(Context, database_name,NULL, database_version); A     } -  - @Override the publicvoid onCreate (sqlitedatabase db) { - Db.execsql (dictionary_table_create); -     } -}

You can then obtain an instance that contains the above constructed method, which is SQLiteOpenHelper called separately according to the read and write requirements of the database getWritableDatabase() getReadableDatabase() . Both methods return the object that represents the database SQLiteDatabase , which contains some methods for SQLite operations.

Android does not add any other restrictions beyond the standard SQLite. It is strongly recommended that you include the self-growing field in the datasheet as a unique identifier for the record to quickly locate a record. This may not be necessary for private data, but when implementing content provider, you must include BaseColumns._ID a unique ID specified by the constant.

Through SQLiteDatabase the query() method, you can perform SQLite queries. The method can pass in various query parameters, such as table name, projection, Select statement, field name, grouping, and so on. If you want to make complex queries, such as using field aliases, use theSQLiteQueryBuilder/code> ,它提供了很多便于构建查询的方法。

Each SQLite query returns one Cursor that points to all records that meet the query criteria. Cursoris the only way to traverse database query results and read row and column data.

For an example of an app that uses the SQLite database on Android, see note Pad and searchable Dictionary.

Database debugging

The Android SDK includes a sqlite3 Database Tools database tool that can be used to browse data tables, run SQL commands, and perform other SQLite database maintenance tasks. For information about how this tool is used, see Managing Sqlite3 databases in a remote Shell

Use a network connection

When the network is available, data can be saved and read through the network in a self-built Web-side service. For operations on the network, use the classes in the following packages:

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

Android Development-API Guide-data storage

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.