Android Storage Options

Source: Internet
Author: User
Tags sqlite database sqlite query

Recently translated an article on Android developer, the original path of the article is the storage Options. This article is about the storage options in Android.
Android provides us with several options for storing robust application data. The method you choose depends on your specific needs, such as whether the data should be private to the current application or accessible to other applications, and how much space your data needs.
Your data is stored in the following ways:

    1. Shared Preferences:
      Store basic private data in a key-value manner.

    2. Internal Storage: (internal storage)
      Store private data on device memory.

    3. External Storage: (External storage)
      Store the shared data on the extended storage.

    4. SQLite Databases:
      Store organized data on a private database.

    5. Network Connection:
      Use your own Web server to store data again.

Android provides a way to expose your data to other Android apps, even including private data, which is content provider. Content provider is an optional control that exposes the read or write permissions of your app's data and is limited by any restrictions you want to add. If you want to learn more about content provider, see the documentation for content provider.

Using Shared Preferences

The Sharedpreferences class provides a framework that allows you to store and retrieve data in key-value format. You can use Sharedpreferences to store any basic data types: Booleans, floats, ints, longs, and strings. This data will continue for the user cycle (even if your app has been killed).
Shared preferences is not strictly used to store user preferences, such as what ringtones the user chooses. If you are interested in creating user preferences for your app (user preferences), look at Preferenceactivity, which provides an activity framework to create the user preferences, which automatically uses the shared Preferences.

You can use the following methods to get a Sharedpreferences object for your app:
Getsharedpreferences (): If you need multiple preferences files that are distinguished by name, you can use this method to differentiate these files with the first parameter.
Getpreferences (): If you only need to provide a preferences file for your activity, you can use this method. Because this is just a preferences file for your activity, you don't have to provide a name to differentiate it.

To write the value:
1. Call edit () to get sharedpreferences.editor.
2. Use these methods Putboolean () and so on to add values.
3. Commit () to submit these new values.

Use the Getboolean () method to read the stored value.

This is an example of storing preference for keyboard keys in a 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 (); }}
Using internal storage

You can store files directly on your device's internal storage. By default, files that are stored on-premises are private to your app and are not available to other apps. When the user uninstalls your app, the files are also removed at the same time.
In order to create and write a private file to the internal storage:
1. Call the Openfileoutput () method, which returns a FileOutputStream.
2. Write to the file using write ().
3. Use Close () to turn off our stream (stream).

For example:

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

Mode_private will create a file (or replace a file with a duplicate name) and make it private to your app.
Other modes to choose from are: Mode_append, mode_world_readable, and mode_world_writeable.

To read a file from the internal store:
1. Call Openfileinput (), which returns the FileInputStream.
2. Read the bytes from the file with read ().
3. Close the file stream with close ().

TIP: If you want to store a file in your app while compiling, store your files in this project directory: res/raw/. You can open it with Openrawresource (), pass the parameter r.raw.< file name >. This way back to InputStream, you can use this stream to read the file. (But you can't write to the original file)

Store cache files

If you want to cache some data instead of storing them all the time, you can use Getcachedir () to open a file that refers to the internal directory where your app stores temporary cache files.
Android may delete these cache files to free up space when the device has insufficient internal storage space. However, you should not rely on the system to clean up these cache files. You should control the addition and deletion of cache files and keep the space they occupy within a reasonable range (e.g. 1MB). These files will be removed when the user uninstalls your app.

Other useful methods

Getfilesdir ():
Gets the absolute path to the directory where your internal files are stored by the file system.
Getdir ():
Create (or open a directory that already exists) an internal storage space.
DeleteFile ():
Delete a file in the internal store.
FileList ():
Returns a list of files that are currently stored by your app.

Using Extended storage

Each Android device supports external storage for storing files. External storage can be a medium that can be removed (such as an SD card) or an internal storage (not removable). Files stored in external memory are globally readable and can be modified by users who allow USB mass storage.
Note: If the user adds external storage or removes media from the computer, the external storage becomes unavailable. And your files stored in external memory will not be guaranteed. All applications can read and write files placed in external memory and they can also delete them.

Permission to get External storage

In order to read and write files on external storage, your app must acquire Read_external_storage and Write_external_storage system permissions. For example:

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

If you want to read and write files at the same time, you only need to add write_external_storage permissions, because it already includes Read permissions.

Tip: Starting with Android 4.4, these permits are not required if you only read and write your app's private files. For more content, see saving files that is app-private.

Check the availability of the media

Before you manipulate external memory, you should call Getexternalstoragestate () to check whether the current medium (external storage directory) is available. This media will be added to the computer, lost, read-only, or in other states. For example, you can use the following method to detect the availability of storage media:

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

The Getexternalstoragestate () method returns other states, such as whether the media is being shared (connected to a computer), lost, mistakenly removed, and so on. When your app requires external storage permissions, you can use these return values to tell the user the state of the current external storage.

Store files that can be shared with other apps

Typically, new files that users can get through your app should be stored in a common place where other apps can access them and users can easily copy them from the device. When doing this, you should use one of the shared public directories, for example: music/, pictures/, and ringtones/.
Call the Getexternalstoragepublicdirectory () method by passing a type of directory that you need, such as Directory_music, Directory_pictures, Directory_ RINGTONES (ringtone directory), etc., to get the files in the corresponding public directory. By storing your files in the appropriate directory, the system's scanners will classify your files. (for example, the ringtone will be set as the ringtone's directory in the system, not music)
For example, here is a way to create a directory for a new album in the public Photo catalog:

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

Hide your files. Place a file scanner to scan it (hide your files)
You can include an empty file named. Nomedia in your external memory directory (the prefix of the note in the file name). This will place the Android system to get your files and make them available to other apps through Mediastore content provider. However, if your files are indeed private to your application, you should store them in the app's private directory (save them in an App-private directory).

Store private files for your app

If you want to deal with files that you do not want to use for other applications (such as images or sound effects that are only used by your app), you should use the private storage directory in external storage by calling Getexternalfilesdir (). This method also requires a parameter to the type of the molecular directory (for example, directory_movies). If you do not need a special external media directory, pass NULL to go past the root directory of your private application directory.
Starting with Android version 4.4, read_external_storage or write_external_storage permissions are no longer required to read and write files in your app's private directory. So you only use the lower Android version by adding the Maxsdkversion attribute to declare this permission, as follows:

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

Note: This directory and its contents will be deleted when the user uninstalls your app. Similarly, the system scan will not read the files in these directories, so mediastore content provider will not get their contents. Similarly, you should not use these directories to store files that are ultimately owned by users, such as photos or music that you buy, which should be stored in a public directory.

Sometimes, an Android device that has some memory allocated as an external storage may still provide an SD card slot. When on Android 4.3 or lower, the Getexternalfilesdir () method only provides internal allocation (memory) permissions and your app cannot read and write to the SD card. However, starting with Android version 4.4, you can get permission for the above two directories by calling the method Getexternalfilesdirs () that returns an array of files. The first entry in the array is the primary external storage, and you should use this address directory unless it is full or unavailable. If you want to get these two directories at the same time on Android 4.3 or below, you can use the static method Contextcompat.getexternalfilesdirs () in the Support library.
This method also contains an array of files, but there is only one entry on Android 4.3 or lower.

Note: Although directories provided by Getexternalfilesdir () and getexternalfilesdirs () cannot be accessed by Mediastore content provider, they have Read_external_ Other applications with storage permissions can access all external storage including the files in the above directory. If you want to completely restrict access to your files, you should write your files to the memory store.

Store cache files

Call the Getexternalcachedir () method to open the cache file that you think should be stored on the external memory. If the user uninstalls your app, the files will be automatically deleted.
Similar to Contextcompat.getexternalfilesdirs (), as we mentioned above, you can also call
The Contextcompat.getexternalcachedirs () method accesses the cache directory on a level two external memory directory (if accessible).

Tip: In order to save your file space and ensure the performance of your app, it's important to manipulate your cache files in detail and delete useless caches in your app's life cycle.

Working with databases

Android provides complete support for the SQLite database. Any database you create can be accessed by name in your app, but not in the app.
Android recommends creating a new database by creating a subclass of Sqliteopenhelper and overloading the OnCreate () method, in which you can create a table in the database with the SQLite command.
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 get an instance of your sqliteopenhelper through the constructors you define. Call Getwritabledatabase () and Getreadabledatabase () respectively to read and write the database. They all return the Sqlitedatabase object and provide the appropriate method for our database operations.

You can use SQLite query statements by using the Sqlitedatabase query () method of parameters including table names, selection criteria, columns, sorting, and so on. For complex queries like these that require column aliases, you should use a sqlitequerybuilder that provides a lot of handy ways to create query statements.

Each SQLite query returns a cursor that points to all rows found through this query. The cursor is usually a mechanism to help you navigate the results of a database query.

For example, you can look at the note pad and the searchable dictionary app to see how to use the SQLite database in Android.

Database debugging

The Android SDK contains a sqlite3 tool that helps us navigate through the contents of the table, run database directives, and use other useful database functions. See examining Sqlite3 databases from a remote shell How to use this feature.

Note: Android does not impose any restrictions on sqlite. We recommend that you include a self-growing range in your table that we can use to quickly locate a record. This is not necessary for private data, but when you declare a content provider, you must use the BASECOLUMNS._ID constant to include a unique ID.

Use a network connection

You can use the network (when it is available) to store and fetch data. To do a network operation, use the following classes in the bread:

java.net.*android.net.*

Android Storage Options

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.