Bi-Chinese Translation

Source: Internet
Author: User
Tags sqlite query

Data storage and application installation location under Android platform

Data storage

You can store your app's data in a database, in a file, or in preferences, or inside and outside of a memory card, or you can turn on a data backup service to allow users to store and recover data from applications and systems.

Storage mode

Android provides several ways for us to persist application data. We can choose the appropriate method according to the specific needs, such as whether the data to be stored is only used for its own application, or other applications and users can also access, such as the size of the data required space.
There are several ways to store data:
1. Shared Preferences (android proper noun, preference)
Store privatized data as key-value pairs
2. Internal Storage Internal Storage
Store private data inside the device
3. External Storage External Storage
Store public data on a shared external zone
4. Sqlite Databases Database
Storing structured data in a private database
5. Network Connection Internet connection
Store data on your own Web server
Android provides a way for you to expose your own private data to other app--contentprovider (content providers). A content provider is an optional component that can read and write your app data publicly, and you can add some restrictions.

Using Sharedpreferences Storage

The Sharedpreferences class provides a schema that allows you to save and retrieve the underlying data type of a persisted key-value pair. You can use it to save any basic data type: Boolean, float, integer, long, String. This data will persist in the user's mobile app (even if the app is killed).
To get sharedpreferences, you can use one of the following two methods:
-Getsharedpreferences () When you need multiple preference files that are distinguished by name, you can use this method to distinguish them by the first parameter.
-Getpreferences () Use this method when your activity only needs a preference file. Because he's for your activity. Is the only preference, you do not need to provide a name.
Write Data:
1. Call the edit () method to get an object: Sharedpreferences.editor.
2. Add values using Putboolean (), putstring () These methods
3. Commit value with commit () method
Read data:
Use sharedpreferences methods such as: Getboolean () and getString ().
Here's an example: Save Silent button Mode in Calculator

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

You can save the file directly inside the device application internal storage, by default, the internal file is private, other applications and users can not access. When the user uninstalls the app, the files are removed.
Create and write a private file to the internal storage space:
1. Call Openfileoutput the name and operation mode of the incoming file, the return value is a FileOutputStream
2. Write something in the file ()
3. Close the Flow method close ()
For example:

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

Mode_private the file to be created is private to the app. Other models also have mode_append,mode_world_readable_mode_world_writeable.
To read a file from an internal store:
1. Call Openfileinput (), pass in the name of the file to be read, return FileInputStream
2. Read the file bytes with the Read () method
3. Close the Stream
Suggestions:
If you want to save a static file at the compile time of your app, save the file in the project's res/raw/directory. You can open it with the Openrawresource () method and pass in the R.raw. The resource ID. The method returns a read stream that you can use to read the file, but not write to it.

Save cache file

If you want to cache the data instead of persisting it, you should use Getcachedir () to open a file that represents the internal directory where the application can save the temporary cache file.
When the internal space is low, Android will erase the cache files to restore space. However, you should not rely on the system to clean up for you, you should maintain the cache file yourself, maintain a reasonable space consumption limit, such as 1MB, when the user uninstall the application, these files are removed.

Other useful methods

Getfiledir ()
Gets the absolute path to the internal file Store file directory
Getdir ()
Create or open an internal storage directory
DeleteFile ()
Delete the internal files of the storage child
FileList ()
Returns an array of files stored by the app

Using external storage

Each Android-compatible device supports external storage to save files. This is a media (SD card) or internal (non-removable) space that can be removed.
Externally stored files are globally readable and can be modified when the user connects to the computer using USB.

Attention:
If the user mounts the external storage on the computer, or removes the media, the external storage cannot be opened, and the files stored in the external file do not have any security protection. All apps can read and write the files here, and they can be removed.

Get access to external storage permissions

In order to read or write files to an external storage space, your app must request permission to read external storage or to write to an external storage space. Like what:

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

When you need to read and write a file, you only need to declare the Write_external_storage permission, because it implicitly contains the Read permission.
Note:
Android + start, if you naturally read your app, these permissions are not needed.

Check if multimedia is mounted

Before you can use external storage, you need to call Getexternalstoragestate () to check if the media exists. It may be mounted on a computer, lost, read-only, or other state. For example, here are some ways to check if you can get:

/* 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;}

Other states returned by the Getexternalstate () method you may want to check whether the media is shared by the computer, whether it is not mounted at all, etc., and you can use this information to inform the user when they need the method media.

Save files that can be shared by other apps

In general, new files that users can get through the application should be saved to a common location on the device, which other applications can access, and users can easily copy from their devices. When doing so, you should use a shared common directory, such as music/,pictures/,ringtones/.
Get the appropriate common directory file, call Getexternalstoragepublicdirectory (), and pass in the directory of the type you want, such as Directory_music, Directory_pictures,directory_ RINGTONES, or other. By saving your files to the appropriate media type directory, the system's media scanner can correctly categorize your files (for example, the ringtone appears in the system as the ringtone directory, not the music).
For example: Here's a way to create a directory for a new photo, in the public picture directory:

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 the app's private files

If you are working with files that you do not want to be used by other apps (compared to text or sound effects), you should call the Getexternalfiledir () method to use a private storage directory. This method uses a type parameter to the area molecular directory. If you don't need a special media directory, pass in NULL to receive your app's root directory.
android4.4 start, read and write files do not need permission, so you can declare the required permissions, the lower version of Android can add the maximum version of the properties

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

Note: When the user uninstalls the app, these directories and contents will be deleted, and the system media scanner will not read these files in these directories, so they cannot be accessed by Mediastore ContentProvider. Like this, you can't use these directories that are ultimately owned by your users, such as photos you edit with your app, or music that users buy, which should be saved in the public directory.
Sometimes, a device is assigned to an internal memory as an external memory, and an SD card slot is provided. When such a device is running Android 4.3 or lower, the Getexternalfilesdir () method only provides internal storage and the application cannot read and write to the SD card. Starting with Android 4.4, you can access these two locations by calling Getexternalfilesdirs (), which returns an array of file entries for each location. The first element in the array is considered to be the primary external memory, and you should use this location unless it is not available. If you want to access both possible locations and also support Android 4.3 and low, use the static method of the support library, Contextcompat.getexternalfilesdirs (). This also returns an array of files, but always contains only one entry at Android 4.3 or lower.
Note: Although Getexternalfilrdir () and getexternalfiledirs () cannot be accessed by the content provider, other apps that have read external permissions can access these. If you need to fully display access to your files, you should use internal storage instead of it.

Save cache file

Opening an external file means that you should save the cache file, call Getexternalcachedir (), and if the user uninstalls the app, the files will be deleted automatically.
Similar to Contextcompat.getexternalfilesdirs (), you can access a cache directory on level two external storage (if any) through Contextcompat.getexternalcachedirs ().

Tip: In order to preserve file space and maintain app performance, it is important to manage cache files carefully and remove unwanted garbage through the app's lifecycle.

Working with databases

The SQLite database is supported by Android. Supports all of the databases that you create in your app by name. But not out of the app.
The recommended way to create a database is to write a class that inherits Sqliteopenhelper and overrides the OnCreate method, and you can execute a SQL command to build the table, for example:

 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 use the constructor of your defined class to get an instance of Sqliteopenhelper, read and write data from a database, call Getwriteabledatabase () and Getreadabledatabase (), They all return a Sqlitedatabase object that represents the database and provides method manipulation data.
You can perform SQLite query with Sqlitedatabase query () method, he accepts a variety of query parameters, such as query tables, items, query conditions, minute queries, etc., for complex queries, such as the need for column aliases, you need to use Sqlitequerybuilder, It provides several convenient ways to build query conditions.
Each SQL query returns a cursor that points to all rows of the query. This cursor can always navigate to the results of rows and columns read by the database query.

Database mode

The Android SDK includes a Sqlite3 database tool that allows you to open the contents of the table, run SQL statements, and other useful functions on the data.

Use a network connection

You can use the network to store and retrieve data in your own service, and in the network operation, use the following package:
-java.net.*
-android.net.*

Application Installation Location

Starting with Android API 8 (android2.2), you can have your app installed on an external storage space (such as the device's SD card), which is an optional feature that you can declare the location of the app with this attribute: Android:installlocation, If this attribute is not declared, your application is installed in the internal storage space and cannot be moved to an external storage area.
To allow the system to install your app in an external area, modify the manifest file, introduce the Android:installlocation attribute as its element, the value is preferexternal or auto, for example:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    android:installLocation="preferExternal"    ... >

If you declare preferexternal, you request the app to be installed in an external space, but the system will not guarantee that the app will be installed externally. If the external storage space is full, the system will be installed in the internal storage space, the user can switch in two places.
If you declare auto, which means your app may be installed externally, but you don't have a preference for an installation location, the system will install your app based on several factors, and users can still switch in two places.
When your app is installed in an external storage space:
-As long as the external storage area is mounted, there is no effect
-The. apk file is saved in the external space, but all private user data, database,. dex files, and local code are saved in internal device memory
-The application's only container storage is encrypted with a randomly generated key that can only be decrypted by the original installation device. Therefore, the application is installed on an SD card and only that device is applicable.
-Users can set up mobile apps to internal storage via the system.

Warning: When a user uses a computer to connect to a mobile phone to share files or not mount an SD card, external storage will be detached from the device and all external applications will be killed immediately.

Applications that should not be installed on the outside

For your application to always run well, if it uses the following attributes, you should not let your installation be external, because references can have some bad consequences when the external is not mounted.
Services:
The service you run will be killed and will not be restarted when the external storage is mounted. But you can register an externally mounted broadcast intent, it will notify you that external storage can be obtained, at which point you can restart your service.
Alarm Services
Your registered alarm will be canceled and you must re-register when the external storage is re-mounted
Input Method Engines
Your input method will be replaced by default, when re-mount, you can open the system settings, re-select your input method
Live Wallpapers
Your gallery will be replaced by the default gallery. When you re-mount, you can choose your own library
APP Widgets
Your app gadget will be removed from the screen, and when you re-mount it, your app gadget won't appear until the system resets the home app (usually after the system restarts).
Account Managers
The account you created will disappear until you re-mount
Device Administrators
Your device receiver can not be used, have the consequences of not met, re-mount may be useless
Broadcast receivers listening for "boot completed"
The broadcast of the system restart is sent before the external storage is mounted, and if the application is installed externally it will not receive this broadcast
If your app uses some of the above, you can't allow it to be installed on an external storage device, and by default the system won't allow your app to be installed on an external storage device, so you don't have to worry about existing apps. However, if you are sure that your app will never be installed externally, you can declare this: android:installlocation= "internalonly". Although it does not change the default behavior, it highlights the state of the app and is a reminder to you and other developers.

Applications that should be installed on the outside

Simply put, all of the features mentioned above are safe to install on external storage devices. The big game is a classic, because the game does not need to provide redundant services when the interaction, when the external storage device is not available, the game was killed, and there is no significant impact when the external storage device is re-mounted, the user restarts the tour (assuming that the game is in the activity's life cycle of the state saved).
If your app needs some apk files, you should be careful to consider whether the app should be allowed to be installed on an external storage device, so users can reserve some space for internal storage.

Bi-Chinese Translation

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.