"Android API Guides (iii)" Data Storage--storage Options

Source: Internet
Author: User
Tags sqlite database sqlite query

Android offers several options for permanently storing mobile data, and we choose to store it in a way that depends on the specific needs we store, such as whether your data needs to be exposed to itself, whether the data can be used by other applications, or how much data you want to store.
The data is stored in the following ways:
Shared Preferences
Stores private raw data through key-value pairs of XML types.
Internal Storage Internal storage
Store private data via phone memory
External Storage External storage
Store the exposed data in the device's external share
SQLite Databases Android native Internal Database
Storing structured data in a private database
Network Connection Internet connection
Storing data on a network server
Android also provides a component –content-providers to make private data public, as described in content-providers reference documentation.

I. Use of Shared Preferences
The Sharedpreferences class provides a complete framework for storing private information permanently in the form of key-value pairs. We can use the Sharedpreferences class to store any type of data, including Booleans, floats, ints, longs, and strings. And the data will be saved throughout the session, even if your app is turned off.
There are two ways to get sharedpreferences objects:
1, getsharedpreferences ()-If you want to get a general preferences object that is distinguished by a key name, use this method.
2, getpreferences (int)-If your entire activity requires only one preferences, you do not need to provide a key name. Use this method.
How to write value values:
1. Use the edit () method to get a Sharedpreferences.editor object.
2. Add values by means similar to Putboolean () and putstring ().
3. Associate the value of the editor with the value of the Sharedpreferences object.
Read the value values through the methods of the Sharedpreferences class, such as Getboolean () and getString ().
Example code:

 Public  class Calc extends Activity {     Public Static FinalString Prefs_name ="Myprefsfile";@Override    protected void onCreate(Bundle State) {Super. OnCreate (state); . . .//Restore preferencesSharedpreferences settings = getsharedpreferences (Prefs_name,0);BooleanSilent = Settings.getboolean ("Silentmode",false);    Setsilent (silent); }@Override    protected void OnStop(){Super. OnStop ();//We need an Editor object to make preference changes.      //All Objects is from Android.context.ContextSharedpreferences settings = getsharedpreferences (Prefs_name,0);      Sharedpreferences.editor Editor = Settings.edit (); Editor.putboolean ("Silentmode", Msilentmode);//Commit the edits!Editor.commit (); }}

Second, the use of internal Storage
You can store the data directly in the internal storage, but in general, the data stored internally for the program is private, other programs are inaccessible, that is, when the program is uninstalled, the data will be removed together. We generally put internal files in the data/data/corresponding application directory.
The process of creating or writing a document to an internal store is as follows:
1, call the Openfileoutput () method, the parameter is the file name and type, return a FileOutputStream object.
2. Write to document with write ()
3. Close the document with close ()
Example code:

String"hello_file";Stringstring"hello world!"Context.MODE_PRIVATE);fos.write(string.getBytes());fos.close();

Mode_private will create or replace files of the same name, and this file is only available for this program. Other models are: Mode_append, mode_world_readable, and mode_world_writeable.
If we have read a fixed file, you can save the file you want to access in the R.raw directory at compile time, and then call Openrawresource (), the parameter is R.raw., returns a InputStream object through this stream, Read the content you want to read. (You may not write to this file.) )
Save Temporary files
If you do not want to permanently save some data, you can create a file in the system directory by calling the Getcahedir () method to save the temporary data. The method return value is the path where the temporary file is saved.
When the internal storage of the system is almost full, the system will automatically clean up the temporary files, but you can not rely on the system to automatically clean up temporary files, you need to set the maximum size of temporary files, and periodically delete temporary files. When the user uninstalls the app, the temporary data is deleted.
Other useful methods
Getfilesdir ()
Gets the absolute path to the saved file.
Getdir ()
Create or open an existing internal storage file.
DeleteFile ()
Delete a file that is stored internally.
FileList ()
Returns a list of files in the app's directory.

Iii. use of external storage
Any Android compatible phone supports sharing files that you save in "external storage". The so-called "external storage" can be stored in removable SD cards, but also in non-removable internal storage. And when we connect the computer via USB, we can modify these files.
Note: When we load external storage on the computer, the corresponding files are not accessible in the phone. Files stored externally are not protected by security, and users can modify or delete the file arbitrarily.
access to external storage
You must have Read_external_storage or Write_external_storage permissions to access or write to externally stored files.
In the manifest.xml of the project, modify:

...>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    ...</manifest>

When we want to read and write, we just need to get write_external_storage permission.
Note: From the 4.4 release, you do not need to access and write files that are private to the application.
Check the availability of media
Before we can use externally stored files, we must check the availability of the file, that is, whether the file is read-only, hidden, or otherwise. We will use Getexternalstoragestate () to return a string object. Confirm the status of the current file by using a string value such as Media_mounted,media_mounted_read_only. Two ways to check the availability of files are provided below:

/* ChecksifExternal storage isAvailable for Read  and Write*/publicBooleanIsexternalstoragewritable () {String state = Environment.getexternalstoragestate ();if(environment.media_mounted.equals(state)) {return true; }return false;} /* ChecksifExternal storage isAvailable to  atLeastRead*/publicBooleanIsexternalstoragereadable () {String state = Environment.getexternalstoragestate ();if(environment.media_mounted.equals(State) | | Environment.media_mounted_read_only.equals(state)) {return true; }return false;}

save files that can be shared by other apps
We usually put the files we want to share under the file directory with shared properties, so how do we create a file directory with shared properties? Call Getexternalstoragepublicdirectory () to create a file directory that sets the properties and names of the file directory by parameter directory type and directory name.
Instance code:

publicgetAlbumStorageDir(String albumName) {    // Get the directory for the user‘s public pictures directory.    new File(Environment.getExternalStoragePublicDirectory(            Environment.DIRECTORY_PICTURES), albumName);    if (!file.mkdirs()) {        "Directory not created");    }    return file;}

Save private file
You can create a hidden file directory by calling the Getexternalfilesdir () method, and you can specify the type of the directory by setting the value of the parameter, such as Directory_movies, which indicates that the file in the file directory is of the video type.
As mentioned above, you can access externally stored files without having to set permissions after 4.4. The lower version requires the following settings, similar to the preceding:

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

Note: When the user uninstalls the app, the file is removed together. Because the file is not scanned by the file system, the content provider component is inaccessible to these files. Therefore, if the files that the user generates in this program cannot be saved in the private directory, the user cannot find the files through other apps.
Sometimes, the device uses an internal storage partition as an external storage, so the call to the Getexternalfilesdir () method does not have access to the internal stored files that are zoned for external storage in versions 4.3 and below. But after the 4.4 release, call the Getexternalfilesdir () method, we can access the two-part file. This time the Getexternalfilesdir () method returns a file name entry, and the first entry is the directory that is zoned for external storage. And this directory is the base directory, unless the directory is full or inaccessible, this portion of the storage is preferred.
Of course, if you don't like the API of this design, you can use the static method Contextcompat.getexternalfilesdirs () in the Support library.
Note: Although files in a private directory cannot be used by the content provider component, they are stored in the internal storage if they want to be completely confidential, because files in the private directory can be accessed by applications with Read_external_storage permissions.
Save Temporary files
You can call Getexternalcachedir () to create a temporary file, just as you would save a temporary file in the internal store. Also, the uninstallation is removed.

Iv. use of the database
Android comes with a SQLite database, but it can only be used in the app that created the database, and other apps can't.
The recommended way to create a database is to create a class that inherits Sqliteopenhelper and override the OnCreate () method.
Examples are as follows:

 Public  class dictionaryopenhelper extends sqliteopenhelper {    Private Static Final intDatabase_version =2;Private Static FinalString Dictionary_table_name ="dictionary";Private Static FinalString 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 get a Sqliteopenhelper object according to the method you specified, and then call the Getwritabledatabase () and Getreadabledatabase () method to get the Sqlitedatabase object, The function of the database is accomplished by manipulating the object.
Sqlitedatabase objects can be queried by calling query (), and more complex queries, such as getting column names, can be queried by Sqlitequerybuilder objects.
Each SQLite query will get the cursor. The cursor is an index that only wants the data that you want to query.
Database Debugging
The Android SDK contains a database called Sqlite3, and we can do a trial operation.

V. Use of the Internet connection
We can also store and recover data from servers on the web, no longer detailed here.

"Android API Guides (iii)" Data Storage--storage Options

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.