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 the developer's point of view, it can be divided into the following five methods:
- SharedPreferences
- Internal Storage space
- External Storage space
- SQLite Database
- Internet
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:
- Shared 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 to the Android Developer Guide, which is unique here.
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.
- 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/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.
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
FileInputStream input = Context.openInputFile(filename); input.read(); input.close();
C. List all created files
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.
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.
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.
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.
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.
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.
- 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 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.
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:
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.
- 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.
The previous article mentioned the trouble of transferring 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 operation. Use standard crude statements, contentresolver. Query (), update (), delete () insert (). For details, see contentresolver.
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.
- Internet
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 damage is caused by user traffic. Please refer to the previous article.
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?
References: http://developer.android.com/guide/topics/data/data-storage.html