Android Development Notes: Detailed data storage methods _android

Source: Internet
Author: User
Tags data structures documentation sqlite sqlite database
Whether it is God horse Platform, God Horse development environment, God Horse software program, data are the core. For the development platform, if the data storage has good support, then the development of the application will have a great role in promoting.
In general, there are three ways to store data: One is a file, one is a database, and the other is a network. Where files and databases may be used a little more, the file is easy to use, the program can define its own format; The database used a bit annoying lock some, but it has its advantages, such as in the massive data performance is superior, there is query function, you can encrypt, can add locks, across applications, cross-platform and so on; For the more important things, such as scientific research, exploration, aviation and other real-time data acquisition needs to be transferred to the data processing center for storage and processing.
For the Android platform, it's stored in the same way, by the way the overall score, but also files, databases and networks. But from the Open in terms of the sender's perspective it can be divided into the following five ways:
1.SharedPreferences Sharing Preferences
2.Internal Storage internal storage space
3.External Storage External storage space
4.SQLite Database Databases
5.Internet Network
Each of these methods have their own advantages and disadvantages, according to different actual conditions to choose, and can not give a unified standard. Here are a few ways to talk about their pros and cons and the most appropriate usage:
1.Shared Preferences Sharing preferences
Sharedpreferences is used to store some basic data types that are similar to key/value, and note that it can only store basic data types, i.e. int, long, Boolean, String, float. In fact, it's exactly the equivalent of a hashmap, except that the value in HashMap can be any object, and the values in Sharedpreferences can only store basic data types (primitive types).
For the use of this method, you can refer to the Android Developer Guide, not repeated here.
In this way, the best place to Sharedpreferences is to save configuration information because many of the configuration information is key/value. In fact, the most used sharedpreferences in Android is also used to save configuration (settings) information, as in settings in the system, as well as settings in each application. And, in Android, to save configuration information for ease of use with sharedpreferences, it's designed to be preferenceactivity for encapsulation. That is, if you want to create a configuration (settings) in your application, you can use preferenceactivity and some related components specifically for preference, without having to create, read, and save them directly sharedpreference , these components in the framework do these things for you.
To talk about some of the tricks of 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 to a string, and then restore it when you remove it; again, if you want to save an object, you can serialize the object to a sequence of characters, or to a string (Object.ToString ()), or save its hashcode (Object.hashcode ()) as value.
In short, sharedpreferences is very convenient to use, can be flexible application, because it is simple and convenient, so can use it as far as possible not to use files or databases.
1.Internal Storage Internal storage space
The so-called internal storage and external storage, refers to whether the phone is built-in. Cell phone's built-in storage space, called internal storage, it is a mobile phone once the factory can not be changed, it is also one of the hardware indicators of the mobile phone, usually the larger the cell phone built-in storage space means that the higher the price of mobile phones (many places call it the phone memory, but we do software to know that this is not accurate, Memory is the place where a hand is stored in a program, data, and instruction; This should be the memory of the phone's internal storage, not the memory in the strictest sense.
The internal storage space is very limited, so it is valuable, so we have to avoid the use of as far as possible, in addition, it is the system itself and the system application of the main data storage location, once the internal storage space is exhausted, the mobile phone can not use. So for the internal storage space, we should try to avoid using. The shared preferences mentioned above and the SQLite databases discussed below are also stored in the internal storage space.
Android itself is a Linux operating system, so its internal storage space, for applications and users is the "/data/data" directory. Compared with other (external storage), it has the advantages of stable, convenient storage, simple operation and more security (because it can control access rights). And its only drawback is that it is relatively limited, more valuable.
Although it is very easy to know the path of the program itself, all the application data paths are "/data/data/app-package-name/", all the data used by the program, such as the Libs library, Sharedpreferences are stored under this path. But we had better not use it, or do not refer directly to this path.
There are two main ways to use internal storage, one is file operation and the other is folder operation. Either way, the context provides the appropriate function to support, the use of the context is not only easy to operate, the most important thing is that the context will help us manage these files, but also to help us to control the access to files. First come to the system next in the context of the functions of File and folder operations.
A. Create a file and open it into a file output stream, you need to supply a string as the filename
Copy Code code as follows:

FileOutputStream output = context.openoutputfile (filename, context.mode_private);
Output.write (data);/Use output to write whatever
Output.close ();

B. Similarly, if you want to open a file as input, you only need to provide a filename
Copy Code code as follows:

FileInputStream input = context.openinputfile (filename);
Input.read ();
Input.close ();

c. List all the files that you have created
Copy Code code as follows:

string[] files = context.filelist ();
for (String file:files) {
LOG.E (TAG, "file is" + file);
}

D. Delete files, can be created to be able to delete, of course, will also provide a delete file interface, it is also very simple, only need to provide file name
Copy Code code as follows:

if (context.deletefile (filename)) {
LOG.E (TAG, "delete file" + filename + "sucessfully");
} else {
LOG.E (TAG, "failed to delete file" + filename);
}

E. Gets the path of the file created file that returns a file object for the operation path
Copy Code code as follows:

File Filedir = Context.getfiledir ();
LOG.E (TAG, "Filedir" + Filedir.getabsolutepath ();

F. Create a directory that requires incoming directory names that return a file object to the operation path
Copy Code code as follows:

File Workdir = Context.getdir (dirname, context.mode_private);
LOG.E (TAG, "Workdir" + Workdir.getabsolutepath ();

G. View created files as a file object, need to pass in a filename, and return a file object
Copy Code code as follows:

File store = context.openfilestreampath (filename);
LOG.E (TAG, "store" + store.length ());

H. Get cache path, no need to pass in parameters, return file object
Copy Code code as follows:

File Cachedir = Context.getcachedir ();
LOG.E (TAG, "Cachedir" + Cachedir.getabsolutepath ());

Summary of file-related operations, you can draw the following three features:
1. File operation only need to provide file name to the function, so the program itself only needs to maintain the filename;
2. Do not have to create the file object and input, output stream, provide file name can return the file object or input output stream
3. All returned to the path operation are file objects.
As mentioned earlier, the internal storage space is limited, valuable, secure, stable, so should be used to save more important data, such as user information, password secret code, etc. do not need to share data with other applications. can also be used to create temporary files, but be careful to delete them in time. In addition, there is a very important feature of internal storage, that is, when an application is unloaded, the file data for the application's internal storage space will be deleted. The reason the system does this is simply that because the internal storage is limited, it must be available, because once it is full, the system will no longer function properly.
1.External Storage External storage space
To talk about mobile phone external storage space, and the internal storage space, the external storage space refers to the mobile phone when the factory does not exist, users can be free to add in the use of external storage media such as TS Card, SD card, such as flash storage media. These flash media from the initial space of small price expensive, to the current high capacity price is cheap, so almost every support for external storage of mobile phones above have a large capacity (greater than 2G) of the flash card.
Android is no exception, and it fully supports external storage media. More precisely, it relies on external memory cards because, for Android, many system applications cannot be used without external memory cards, such as multimedia-related applications. Although Android is very dependent on, but the external memory card also has its own characteristics, its biggest advantage is that storage space is large, basically you can use unlimited, and do not worry about to clean up the data. For now, many programs are using an external memory card, but there are few programs to actively clean up the data, so no matter how big your SD card is, its free space is getting less. Unlike internal storage, when a program unloads, the file data that it creates on the external store is not purged. So the responsibility to clean up the external storage space to the user himself, every once in a while to check the SD card, found useless data immediately deleted. The disadvantage of external storage is not very stable, for the Android phone can say, very unstable, its own flash media is prone to problems, SD card in the state of normal use is very much.
To start with, external storage-related usage methods and APIs:
A. Check media availability checking the availability of media
As mentioned earlier, the stability of external storage media is very poor, so you must check its availability before use, if you can use
Copy Code code as follows:

Final String state = Environment.getexternalstoragestate ();
if (state.equals (environment.media_mounted) | | | state.equals (ENVIRONMENT.MEDIA_READ_ONLY)) {//SD card are ready to US}

B. Get the directory gets the path to the external storage card
In fact, the path to the external memory card is "/mnt/sdcard", so you can access it directly by writing to it. Given the readability and portability considerations, it is recommended to write this:
Copy Code code as follows:

File Sdcarddir = Environment.getexternalstoragedirectory ();

C. for API 8 or greater, there are some the other useful APIs helping to manager files and directories.
If you use API 8 (Android 2.2) or higher, the SDK has several more interfaces for external storage of files and paths, and the documentation also suggests that the starting user will use the SD card more standardized. For example, create the appropriate directory to store the corresponding data, music,picture,video and so on. The application directory has also become "/android/data/package-name/data". Specific use can refer to the documentation, which is not duplicated here. Of course, as with programming specifications, this is just a specification, and you can totally do it without it, but for readability and portability, it's recommended to follow the documentation.
Here's a summary of some and external storage features you should be aware of when using:
A. External storage cards are not available at any time, so be sure to check their availability before using them
B. Data stored on external storage cards is visible to all applications and visible to users (using FileManager), so security is not very good, although the document claims to be able to write private data on an external memory card, but it doesn't seem to work. You can still delete or edit files with FileManager (market FileManager features are powerful enough to allow users to see all the files in the SD card and to manipulate the files they can see).
C. Android phone support to mount the external storage card to the PC as a U disk, when connecting the data line, when the SD card into a U disk connected to another operating system. What that means is that while some of the file attributes (hidden, private, etc.) are on Android, it doesn't necessarily work on the PC, and users can manipulate the files on their PCs (which is the 2nd mentioned).
D. If you use an external memory card to save data, be sure to do extra processing: Where to store the data when the external memory card is unavailable, and how to synchronize the data when available (this is a more painful place, the practical approach is to not allow the user to write the data when the SD card is unavailable, but this user experience is not very good, but as you know, Many applications do so); Your data is corrupted. Of course, common anomalies to consider, such as full space, unable to write, Disk Bad road, and so on.
1.SQLite Database databases
Android's support for the database is good, it integrates the SQLite database itself, each application is easy to use it, or rather, Android relies entirely on the SQLite database, all of its system data and the structured data it uses are stored in the database.
It has the following advantages:
A. It is undeniable that the efficiency is superior
B. Ideal for storing structured data
C. Facilitating the transfer of data between different activity and even different applications
There was an article earlier < deep understanding of data transfer between activity >Talk about the hassle of passing data between different activity and different applications, especially for large data structures, because the activity is a Java object, but you can't create an instance and use it as you would with other classes of objects. 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 the different activity.
D. Specialized ContentProvider to help manage and maintain the database
E. Easy to set access permissions, private or visible
F. Easy to operate, using standard crude statements, Contentresolver.query (), update (), delete () insert (), see Contentresolver
G. Good portability and versatility, using standard SQL statements to achieve crude
the use of the method can be used to refer to the documentation , this is not clear.
1.Internet Network
Network is a relatively unreliable one, because the network stability of mobile terminals, as well as the resulting flow of people can not afford to hurt, the user is more injured. But for very important real-time data, or to be sent to the remote server to deal with, you can also consider using the network real-time delivery. This is a precedent, as is the case with Apple and Google, where iphone devices and Android devices collect information about users without their knowledge, and then send them to Apple and Google's servers without the user's knowledge, known as "tracking doors." In addition, smart phones (especially Android and the hot iphone) above the application will secretly run in the background, collecting user data, and then secretly sent the server, direct damage is user traffic.
In contrast to these several ways, you can conclude:
1. Simple data and configuration information, sharedpreference is preferred;
2. If sharedpreferences is not enough, create a database
3. Structured data, be sure to create a database, although this slightly annoying lock, but the benefits are endless
4. Files are used to store files (that is, not configuration information or structured data), such as text files, binaries, PC files, multimedia files, downloaded files, and so on.
5. Try not to create files
6. If you create a file, if it is a private file or important file, it is stored in the internal storage, otherwise put to the external storage
7. Do not collect user data, do not send to the network, although you also have a lot of helplessness. Users are also helpless, but also innocent, but more helpless
Platform for developers to prepare so many ways is a good thing, but we have to recognize each of the advantages and disadvantages, according to the actual situation to choose the most appropriate. There is also a principle that is the simplest principle, that is, can be handled in a simple way, not in a complex way. such as storing a few data or Simple object, with Sharedpreference also can do, why still 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.