Android Development Notes: Data Storage Methods

Source: Internet
Author: User

Data is the core of Shenma platform, Shenma development environment, Shenma software program. For the development platform, if you have good support for data storage, it will greatly promote application development.
Generally, there are three Data Storage Methods: file, database, and network. Among them, files and databases may be used a little more, files are more convenient to use, and programs can define their own formats; databases may be slightly difficult to use, but it has its advantages, for example, in the case of massive data volumes, the performance is superior, with query functions, encryption, locks, cross-application, and cross-platform functions. networks are used for important tasks, such as scientific research and exploration, real-time data collected by airlines needs to be immediately transmitted to the data processing center through the network for storage and processing.
For the Android platform, its storage methods are similar to these. They are classified as files, databases, and networks in general. But from From the sender's perspective, it can be divided into the following five methods:
1. SharedPreferences sharing preferences
2. Internal Storage space
3. External Storage
4. SQLite Database
5. Internet Network
These methods have their own advantages and disadvantages. They should be selected based on different actual conditions, but they cannot provide unified standards. The following describes their advantages and disadvantages and the most appropriate use cases in various ways:
1. Shared Preferences sharing Preferences
SharedPreferences is used to store basic data types similar to Key/Value pairs. Note that SharedPreferences can only store basic data types, that is, int, long, boolean, String, and float. In fact, it is equivalent to a HashMap. The only difference is that the Value in HashMap can be any object, while the Value in SharedPreferences can only store the basic data type (primitive types ).
For how to use it, refer Android Developer Guide.
In this case, the best choice for SharedPreferences is to save configuration information, because many configuration information is Key/Value. In fact, in Android, SharedPreferences are used most often to save the Settings information. In the system Settings, the Settings in various applications are also used. In addition, for the convenience of saving configuration information using SharedPreferences in Android, PreferenceActivity is used for encapsulation. That is to say, if you want to create Settings in the application, you can directly use PreferenceActivity and some related components specially encapsulated for Preference, instead of directly creating them, read and save SharedPreference. These components in the Framework will do these tasks for you.
Let's talk about some tips when using SharedPreference. It can only save basic data types, but what if I want to save an array? You can process the data, convert it into a String, and restore the data when it is retrieved. For example, if you want to save an object, what should you do, you can serialize an Object into a character sequence or convert it to a String (Object. toString (), or set its HashCode (Object. hashCode () is saved as Value.
In short, SharedPreferences is very convenient to use and can be flexibly applied. Because it is simple and convenient, try not to use files or databases if you can use it.
1. Internal Storage space
The so-called internal and external storage refers to whether the mobile phone is built in. The built-in storage space of the mobile phone is called internal storage. It cannot be changed once the mobile phone leaves the factory. It is also one of the hardware indicators of the mobile phone, generally, the larger the phone storage space, the more expensive the mobile phone will be. (in many places, it is called the mobile phone memory, but we know that this is not accurate when we do software, memory refers to the storage program, data, and instructions when the mobile phone is running. Here, memory should be referred to as memory for internal storage of the mobile phone, rather than memory in a strict sense ).
Internal storage space is very limited, so it is very valuable, so we should try to avoid using; in addition, it is also the main data storage location of the system itself and system applications, once the internal storage space is exhausted, the mobile phone cannot be used. Therefore, we should avoid using the internal storage space as much as possible. The Shared Preferences mentioned above and the SQLite database mentioned below are also stored in the internal storage space.
Android is a Linux operating system, so its internal storage space is the "/data" directory for applications and users. Compared with other (external storage), it features stable storage, convenient storage, simple operation, and more secure (because it can control access permissions. Its only drawback is that it is relatively limited and valuable.
Although it is easy to know the data path of the program itself, the data path of all applications is "/data/app-package-name /", the data used by all programs, such as the libs library and SharedPreferences, are stored in this path. But we 'd better not use this path, or never directly reference it.
There are two main methods to use internal storage: File Operations and folder operations. In either way, the Context provides corresponding functions. Using Context is not only simple and convenient, but also helps us manage these files, it can also help us control the access permissions of files. First, let's talk about the functions related to file and folder operations in Context.
A. Create a file and open it into a file output stream. a String must be provided as the file name.
Copy codeThe Code is as follows: FileOutputStream output = Context. openOutputFile (filename, Context. MODE_PRIVATE );
Output. write (data); // use output to write whatever you like
Output. close ();

B. Similarly, to open a file as input, you only need to provide the file name
Copy codeThe Code is as follows: FileInputStream input = Context. openInputFile (filename );
Input. read ();
Input. close ();

C. List all created files
Copy codeThe Code is as follows: String [] files = Context. fileList ();
For (String file: files ){
Log. e (TAG, "file is" + file );
}

D. To delete a file, you must be able to delete it when it can be created. Of course, the interface for deleting the file is also provided. It is also very simple and you only need to provide the file name.
Copy codeThe Code is as follows: if (Context. deleteFile (filename )){
Log. e (TAG, "delete file" + filename + "sucessfully");
} Else {
Log. e (TAG, "failed to delete file" + filename );
}

E. Obtain the path of the created file. It returns a file object for the operation path.
Copy codeThe Code is as follows: File fileDir = Context. getFileDir ();
Log. e (TAG, "fileDir" + fileDir. getAbsolutePath ();

F. To create a directory, You need to input the directory name. It returns the operation path used by a file object.
Copy codeThe Code is as follows: File workDir = Context. getDir (dirName, Context. MODE_PRIVATE );
Log. e (TAG, "workdir" + workDir. getAbsolutePath ();

G. view the created File as a File object. The File name must be input and the object will be returned.
Copy codeThe Code is as follows: File store = Context. openFileStreamPath (filename );
Log. e (TAG, "store" + store. length ());

H. Obtain the Cache path. No parameters need to be input. The file object is returned.
Copy codeThe Code is as follows: File cachedir = Context. getCacheDir ();
Log. e (TAG, "cachedir" + cacheDir. getAbsolutePath ());

To sum up the operations related to the file, we can obtain the following three features:
1. File Operations only need to provide a file name to the function, so the program only needs to maintain the file name;
2. You do not need to create File objects and input and output streams by yourself. You can return a File object or input and output stream by providing the File name.
3. All objects returned by the path operation are file objects.
As mentioned above, internal storage space is limited, valuable, secure, and stable. Therefore, it should be used to store important data, such as user information, password and other data that does not need to be shared with other applications. It can also be used to create temporary files, but be sure to delete them in time. In addition, there is a very important feature for internal storage, that is, when an application is uninstalled, all the file data of the application in the internal storage space will be deleted. The reason for the system to do so is that the internal storage is very limited and it must ensure its availability, because once it is fully occupied, the system will no longer work normally.
1. External Storage space
Let's talk about the external storage space of the mobile phone. Compared with the internal storage space, the external storage space refers to the external storage space that does not exist when the mobile phone leaves the factory. Users can freely add external storage media such as TS cards when using it, SD card and other flash storage media. These Flash Media are expensive because of the low initial space and low current high capacity. Therefore, almost every mobile phone supporting external storage has a large capacity (greater than or equal to 2 GB) flash card.
Android also supports external storage media. In fact, more specifically, it depends on the external memory card, because for Android systems, if there is no external memory card, many system applications cannot use it, for example, multimedia applications cannot be used. Although Android is very dependent, the external memory card also has its own characteristics. Its biggest advantage is that it has a large storage space. Basically, you can use it without restrictions, and you are not worried about clearing data. For the moment, many programs are using external memory cards, but few programs actively clean up data, so no matter how large your SD card is, it has fewer and fewer available space. Unlike internal storage, when a program is detached, the file data created in the external storage is not cleared. Therefore, the responsibility for clearing the external storage space is lost to the user. He can view the SD card at intervals and immediately delete useless data. The disadvantage of external storage is that it is not very stable. for Android phones, it can be said that it is very unstable, and Flash Memory media itself is prone to problems, and the SD card is in a lot of abnormal states.
Let's talk about how to use external storage and APIs:
A. Check media availability
As mentioned above, the stability of the external storage media is very poor. Therefore, you must check its availability before using it.Copy codeThe Code is as follows: final String state = Environment. getExternalStorageState ();
If (state. equals (Environment. MEDIA_MOUNTED) | state. equals (Environment. MEDIA_READ_ONLY) {// sd card is ready to us}

B. Get the directory to Get the path of the external memory card
In fact, the path of the external memory card is "/mnt/sdcard", so you can access it directly. Considering readability and portability, we recommend that you write as follows:Copy codeThe Code is as follows: File sdcardDir = Environment. getExternalStorageDirectory ();

C. For API 8 or greater, there are some other useful APIs helping to manager files and directories.
If you use API 8 (Android 2.2) or higher, there are several more interfaces in the SDK to operate on External Storage files and paths. We recommend that you use the SD card in a more standard way. For example, create a directory to store the corresponding data, such as Music, Picture, and Video. The application directory is also "/Android/data/package-name/data ". For more information, see the document. Of course, just like a programming specification, this is just a specification. You can leave it alone, but it is recommended to follow the recommendations of the document for readability and portability.
The following summarizes some of the features that should be paid attention to during use and External Storage:
A. The external memory card is not ready for use at any time, so be sure to check its availability before use.
B. the data stored on the external memory card is visible to all applications and users (using FileManager), so the security is not very good, although the document claims that the program private data can be written on the external memory card, but it seems useless. With FileManager, you can still delete or edit files (the FileManager function on the Market is very powerful, allowing you to see all the files in the SD card and the files that can be viewed by operations ).
C. Android mobile phones support mounting an external memory card to a PC as a USB flash drive. When the data cable is connected, the SD card becomes a USB flash drive and connected to another operating system. In Android, although some file attributes (hidden, Private, etc.) do not work on PC, users can operate files on the PC at Will (this is mentioned in point 2 ).
D. if you use an external memory card to store data, you must handle extra exceptions: Where to store the data when the external memory card is unavailable; how to synchronize the data when it is available (this is a headache, the feasible method is that users are not allowed to write data when the SD card is unavailable, but the user experience is not very good, but as you know, many applications do this); your data is damaged. Of course, common exceptions should also be considered, such as full space, failure to write, and bad disk sectors.
1. SQLite Database
Android supports databases very well. It is integrated with the SQLite database, and every application can easily use it. Or, more specifically, Android relies entirely on the SQLite database, all of its system data and structured data used are stored in the database.
It has the following advantages:
A. Being efficient is undeniable.
B. It is very suitable for storing structured data
C. It is convenient to transmit data between different activities or even applications.
Previous Article<Understand data transmission between activities in depth>It is difficult to transmit data between different activities and applications, especially for large data structures, because although an Activity is a Java object, however, you cannot create an instance and use it like other class objects, and you cannot add Setters and Getters to the Activity (although there is no compilation error ). A better solution is to write structured data to the database and then pass their Uris between different activities.
D. A dedicated ContentProvider is used to manage and maintain databases.
E. You can easily set access permissions, private or visible.
F. Easy to operate. Use standard CRUDE statements, ContentResolver. query (), update (), delete () insert (). For details, seeContentResolver
G. Good portability and versatility. You can use standard SQL statements to implement CRUDE.
You can refer to the document for how to use it. It is not clear here.
1. Internet Network
The network is unreliable, because the network stability of mobile terminals and the traffic generated cannot afford to hurt users. However, if real-time data is very important or needs to be sent to a remote server for processing, you can also use the network for real-time transmission. This has already set a precedent. Apple and Google are like this. Both iPhone and Android devices collect user information without your knowledge, then, it is sent to Apple and Google servers without users' knowledge, that is, the so-called "tracking door ". In addition, apps on smartphones (especially Android and the popular iPhone) will secretly run in the background, collect user data, and then secretly send data to the server, direct harm is the user traffic.
To compare these methods, we can summarize the following:
1. SharedPreference is the first choice for simple data and configuration information;
2. If SharedPreferences is not enough, create a database.
3. for structured data, you must create a database. Although this is a little tricky, the benefits are infinite.
4. files are used to store files (that is, non-configuration information or structured data), such as text files, binary files, PC files, multimedia files, and downloaded files.
5. Try not to create files
6. If you create a file, if it is a private or important file, it will be stored in internal storage; otherwise, it will be stored in external storage.
7. Do not collect user data, or send it to the network. Although you have a lot of helplessness. Users are helpless and innocent, but helpless.
It is a good thing that the platform has prepared so many methods for developers. But we need to recognize the advantages and disadvantages of each method and select the most appropriate one based on the actual situation. Another principle is the simplest principle. That is to say, you can use a simple method to deal with it, rather than a complicated method. For example, if you can store several data or simple objects and use SharedPreference, why write a ContentProvider?

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.