Summary of data storage in 67.Android

Source: Internet
Author: User
Tags sqlite database sqlite query

Reprint: http://mp.weixin.qq.com/s?__biz=MzIzMjE1Njg4Mw==&mid=2650117688&idx=1&sn= D6c73f9f04d02ede7a741b45e801d74e#rd

This article will help you quickly learn about the various data storage mechanisms in Android and how to use them in order to create a "directory" in your mind. With this directory, the details of the use of the actual application to query the document can be obtained.

0. Overview

Android provides us with the following storage mechanisms:

    • Shared Preferences: Stores the original type data of the application private in key-value pairs.

    • Internal Storage (internal storage): store Application Private data in the storage space of the device itself

    • External Storage (External storage): store public data in external storage (e.g. SD card)

    • sqlite Databases (SQLite database): storing structured data in a private database

    • Network Connection: store data on your Web server

In the above several data storage methods, we can be based on the actual needs of flexible selection. For example, "whether the data is private or shared with other applications", "How much storage space is needed for the data to be stored", and so on, are some of the issues that we need to consider when choosing a specific data storage mechanism. Let's take a look at the application scenarios and basic usage of these storage mechanisms.

1. Using the shared Preferences

This storage method is used to store raw type data, including Boolean, int, long, float, double, string, and so on. The specific storage method is the key-value pair, if we do not actively delete, the data will persist.

Based on the above, it is easy to conclude that the data that the GKFX preferences is suitable for storage is:

    • The history of the mini-game is highest (integer data);

    • User preferences: Whether to load the picture (Boolean) and whether to turn on Night Mode (Boolean) only when WiFi is enabled;

    • All user data that can be represented by the original type ...

To use shared Preferences, we first get a Sharedpreference object, there are two ways to get this object:

    • getSharedPreferences()-: Use this method to specify a file name for each data file.

    • getPreferences()-When your activity only needs a data file to store user data, this method is your dish.

After getting to a Sharedpreferences object in one of these two ways, we can start writing to it as user data, with the following steps:

    • Call the edit () method to get a Sharedpreferences.editor object

    • By putBoolean() , putDouble() method adds a key-value pair to it

    • Call commit () to commit

In just three steps, we managed to save the user data. So what do we do when we want to get the saved data again? Very simple: only need to get a sharedpreferences after the call getBoolean(),getBoolean() method.

Let's take a look at the sample code from Android Developer:

Public Class Calc Extends Activity {
Public Static Final StringPrefs_name= "Myprefsfile";

@Override
Protected voidOnCreate(BundleState){
Super.OnCreate(State);
. . .

Read the data we saved before from the preferences file
SharedpreferencesSettings=Getsharedpreferences(Prefs_name, 0);
BooleanSilent=Settings.Getboolean("Silentmode", False);
Setsilent(Silent);
}

@Override
Protected voidOnStop(){
Super. OnStop();

Save User Data
sharedpreferences Settings = getsharedpreferences(prefs_name, 0);
sharedpreferences. Editor Editor = settings. Edit();
Editor. Putboolean("Silentmode", msilentmode);

Save the user data after submission takes effect
Editor. Commit();
}
}< /c23>

2. Using internal storage

In this way, the data is stored in the application's private storage space, and other apps do not have access to the storage space, and the data is deleted when the user uninstalls your app. From this we can know that when the data we want to save is used only for this application, and we want it to be "die" with this application, we can use internal storage.

It only takes three steps to create an app private file for data preservation:

    • Called to openFileOutput() get a fileoutputstream (file output stream) object

    • Write data to it using write ()

    • Call write () to close the file output stream before opening

Examples are as follows:

String="Hello_file";
Stringstring="Hello world!" ;

FileOutputStream= openfileoutput(FILENAME,Context. Mode_private);
Fos. Write(string. GetBytes());
Fos. Close();

The parameter in the above method means that the MODE_PRIVATE data file is private to the application and cannot be accessed by other applications.

It is also easy to read data from internally stored files in just three steps:

    • Call and give it the name of the file that we want to read, and it will return to us with an FileInputStream object

    • Reading data from it using the Read () method

    • Call the Close () method to close the previously opened file input stream

Sometimes we want to store some temporary data in the application's private storage space, this time we can use the getCacheDir() method to get the internal directory used to save the temporary cache file. The file stored in this directory has a feature: when the internal storage space is not enough, the system will automatically delete some of the files under this folder. Of course, the only way to do this is to maintain the files in this folder ourselves. Similarly, files in this folder will be deleted when the app is uninstalled.

For a more detailed introduction to using internal storage, refer to the links in the "References" section at the end of this article.

  3. Using external storage

External storage in Android is usually an SD card, and files stored externally are often shared by individual applications. Obviously, when we want to keep the data shared by various applications in the system, we can consider using external storage, on the other hand, because the internal storage of mobile phones is generally smaller than external storage, we should also put some large data files in the external storage. Data files stored in external storage are not deleted as the app is uninstalled.

To read and write files in external storage, we first need to declare the following permissions in the Androidmanifest.xml file:

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

Is that OK? Obviously not, we need to make sure that there are external storage available in the user's phone before using external storage (in case the user's phone doesn't have an SD card at all ...). To implement this is simple, see the official Sample code:

/* Check if external storage can be read/written */
Public BooleanIsexternalstoragewritable() {
StringState= Environment.Getexternalstoragestate();
If (Environment.media_mounted.equals(State)) {
Return True;
}
Return False;
}

/* Check to be able to read only and not write external storage */
Public BooleanIsexternalstoragereadable () {
    String state = environment . Getexternalstoragestate ();
    if ( environment . media_mounted . equals ( State ) | |
        environment . Media_mounted_read_only . equals ( State )) {
        return True ;
    }
    return false ;
} /span>

For some public music, pictures, or ringtone files, we can store them separately in the external storage Music/ Pictures/ Ringtones/ folder. To get a file object representing the above public folder, simply call the Getexternalstoragepublicdirectory () method and pass in a parameter that indicates which folder ( DIRECTORY_MUSIC , DIRECTORY_PICTURES ,, DIRECTORY_RINGTONES etc.) we want to access specifically.

For example, the following method creates a folder in the public picture directory to hold the new album:

Public FileGetalbumstoragedir(StringAlbumname) {
Get the directory for the user's public pictures directory.
file File = new file(environment. Getexternalstoragepublicdirectory(
environment. Directory_pictures), albumname);
if (! File. Mkdirs()) {
Log. E(log_tag, "Directory not created");
}
return file;
}< /c28>

So is there any way we can make this data private if we only store the data in the external storage because the phone is not stored internally? The answer is yes. We simply call the Getexternalfilesdir () method to get a private storage directory in an external store. Data files located in this directory are deleted as the app is uninstalled, after all, they only make sense for the app itself.

Starting with Android 4.4 (API 19), it is not necessary to add a permission statement to read and write this application's private directory located in external storage. So we can add maxSdkVersion properties to the Androidmanifest.xml to show that this permission is only needed before Android 4.4.

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

As with internal storage, there is also a cache folder in external storage that is designed to hold temporary files. To get the file object that represents the cache folder for this app, simply call the Getexternalcachedir () method, which is also automatically deleted when the user unloads the reference.

4. Using the SQLite database

As we mentioned earlier, the SQLite database is used to store structured data, so-called institutional data is data with fixed structure. For example, the score table, payroll, and so on are natural suitable for database storage of structured data.

Android's recommended way to access the SQLite database is to create a subclass of Sqliteopenhelper and override the method in which onCreate() you execute the sqlite command that creates the database table, such as the following code:

Public Class Dictionaryopenhelper Extends Sqliteopenhelper {

Private Static Final IntDatabase_version= 2;
Private Static Final StringDictionary_table_name= "Dictionary";
Private Static Final StringDictionary_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< span>. execsql ( dictionary_table_create );
    }
}

Then we can get an SQLiteOpenHelper instance of the above subclass to start manipulating the database. We can call getReadableDatabase() and Getwritabledatabase () methods separately to read and write to the database. Both of these methods return an SQLiteDatabase object that provides a general way of working with databases such as check and delete.

To perform a query operation on the SQLite database, you can call the SQLiteDatabase query() method. For complex query operations, using Sqlitequerybuilder is a better choice.

Each SQLite query operation returns a cursor object that points to all rows matching the query criteria. For more details about using SQLite in Android, you can refer to the links at the end of this article.

5. References
    • Android Developer: https://developer.android.com/guide/topics/data/data-storage.html (for wall users see here:/http hukai.me/android-training-course-in-chinese/basics/data-storage/index.html)

    • use of SQLite in Android : http://www.cnblogs.com/Excellent/archive/2011/11/19/2254888.html

Summary of data storage in 67.Android

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.