Android Development Note: A detailed description of how data is stored

Source: Internet
Author: User

Whether it is God horse Platform, God Horse development environment, God horse software programs, data are the core. For the development platform, if the storage of data is well supported, then the development of the application will be greatly facilitated.
In general, there are three ways to store data: One is a file, one is a database, the other is a network. Where the file and database may use a little more, the file is more convenient to use, the program can define its own format; database with a little annoying lock some, but it has its advantages, such as the high performance in the massive data, have query function, can be encrypted, can be locked, can be cross-application, cross-platform and so on; is used to compare important things, such as scientific research, exploration, aviation and other real-time collected data need to be transferred over the network to the data processing center for storage and processing.
For the Android platform, it is stored in a way that is also the case, according to the overall score, but also files, databases and networks. But from the Openin 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
5.Internet Network
Each of these ways has its 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 use cases:
1.Shared Preferences Sharing preferences
Sharedpreferences is used to store some key/value similar pairs of basic data types, note that it can only store basic data types, namely, int, long, Boolean, String, float. In fact, it is exactly equivalent to a hashmap, the only difference is that value in HashMap can be any object, and the values in Sharedpreferences only store the base data type (primitive types).
For the use of this method, you can refer toAndroid Developer Guide, there is no repetition here.
In this case, the best place to sharedpreferences is to save the configuration information because many of the configuration information is key/value. In fact, the sharedpreferences used most in Android is also used to save the configuration (Settings) information, in the system Settings in this way, the Settings in each application is the same. And, for the convenience of using Sharedpreferences to save configuration information in Android, it comes specifically with 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 the preference package without having to create, read, and save directly sharedpreference , these components in the framework will do these things for you.
Let's talk about some techniques for using sharedpreference, which can only save basic data types, but what if I want to save an array? You can process the data, turn it into a string, remove it and then restore it, and then, if you want to save an object, what to do, as well, you can serialize the object into a sequence of characters, or to a string (Object.ToString ()), or save it as value in Hashcode (Object.hashcode ()).
In short, sharedpreferences use is very convenient, can be flexible application, because it is simple and convenient, so can use it to try not to use files or databases.
1.Internal Storage Internal storage space
The so-called internal storage with external storage refers to whether the phone is built-in. Mobile phone built-in storage space, called internal storage, it is the phone once the factory can not be changed, it is also one of the hardware indicators of mobile phones, generally speaking, the larger the mobile phone built-in storage space means that mobile phone prices will be more expensive (many places it called cell phone memory, but we do the software know that this is not accurate, Memory is the place where you store programs, data, and instructions when your hands are running, and this should be the memory that is stored inside the phone, not the memory in the strict sense.
Internal storage space is very limited, so it is valuable, so we want to avoid the use of, 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 phone will not be used. So for the internal storage space, we should try to avoid it. The shared preferences mentioned above and the SQLite database to be 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. It is more stable than other (external storage), easy to store, easy to operate, more secure (because you can control access) and other advantages. And its only drawback is that it is more limited, more valuable.
Although, it is very easy to know the path of the data of the program itself, all the application data path is "/data/data/app-package-name/", all the program used data, such as the Libs library, Sharedpreferences are stored under this path. But we had better not use it, or do not refer to this path directly.
There are two main ways to use internal storage, one for file operations and one for folder operations. Either way, the context provides the appropriate functions to support, the use of the context is not only easy to operate, the most important is that the context will help us to manage these files, but also to help us control the access to the file. First, what are the functions of file and folder operations in the context of the system?
A. Create a file and open it as a file output stream, you need to provide a string, 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
Output.close ();


B. Similarly, if you want to open a file as input, you only need to provide a filename

Copy CodeThe code is as follows:
FileInputStream input = context.openinputfile (filename);
Input.read ();
Input.close ();


C. List all files that have been created

Copy CodeThe code is 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, also provides the interface to delete files, it is very simple, only need to provide 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. Get the path to the file created file, which returns a file object for the action path

Copy CodeThe code is as follows:
File Filedir = Context.getfiledir ();
LOG.E (TAG, "Filedir" + Filedir.getabsolutepath ();


F. Create a directory, you need to pass in the directory name, it returns a file object to the action path

Copy CodeThe code is as follows:
File Workdir = Context.getdir (DirName, context.mode_private);
LOG.E (TAG, "Workdir" + Workdir.getabsolutepath ();


G. Viewing the created file as a file object, passing in the filename, returning the object

Copy CodeThe code is as follows:
File store = context.openfilestreampath (filename);
LOG.E (TAG, "store" + store.length ());


H. Get the cache path, no need to pass in parameters, return file object

Copy CodeThe code is as follows:
File Cachedir = Context.getcachedir ();
LOG.E (TAG, "Cachedir" + Cachedir.getabsolutepath ());


summarize the file related operations, you can draw the following three features:
1. File operation only need to provide a file name to the function, so the program itself only needs to maintain the file name;
2. No need to create file object and input, output stream, provide file name can return file object or input output stream
3. The file object is returned for the path operation.
As mentioned earlier, the internal storage space is limited, valuable, secure, stable, so it should be used to save more important data, such as user information, password secret code and other applications do not need to share data. You can also use it to create temporary files, but be sure to delete them in a timely manner. Another important feature of internal storage is that when an application is unloaded, the file data for the application's internal storage is deleted. The reason for this is simple, because internal storage is limited, and it must be guaranteed to be usable, because once filled, the system will no longer function properly.
1.External Storage External storage space
Then talk about the phone external storage space, and the internal storage space, external storage space refers to the phone when the factory does not exist, users can freely add the use of external storage media such as TS Card, SD card and other flash storage media. These flash media are expensive from the initial space and are now cheap for large capacity, so almost every phone that supports external storage has a large capacity (greater than or equal to 2G) of flash cards.
Android is no exception, it fully supports external storage media. In fact, it is to rely on external memory card, because for the Android system, if there is no external memory card, a lot of system applications can not be used, such as multimedia-related applications can not be used. Although Android is very dependent, but the external memory card also has its own characteristics, its biggest advantage is the large storage space, basically you can use unlimited, and not afraid to clear the data. For the moment, many programs are using an external memory card, but there are few programs to proactively clean up the data, so no matter how big your SD card is, it's getting less usable space. Unlike internal storage, when a program unloads, the file data that it creates in the external store is not purged. So the responsibility to clean up the external storage space is lost to the user, 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 Android phones can be said, very unstable, its own flash media is prone to problems, SD card is not normal use of the state is very much.
First, the external storage-related usage methods and APIs:
A. Check media availability checking the availability of the medium
As mentioned earlier, the stability of the external storage medium is very poor, so before use must check its availability, if available to use

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 to the external memory card
In fact, the path to the external memory card is "/mnt/sdcard", so you can write it directly to access it. Given the readability and portability considerations, it is recommended that you write:

Copy CodeThe code is as follows:
File Sdcarddir = Environment.getexternalstoragedirectory ();


C. for API 8 or greater, there is some other useful APIs helping to manager files and directories.
If you are using API 8 (Android 2.2) or higher, then there are several interfaces in the SDK that operate externally to store files and paths, and it is recommended that you use the SD card more standard in the documentation. 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". The specific use can refer to the documentation, which is not duplicated here. Of course, like a programming specification, this is just a specification, you can totally not follow it, but for readability and portability, it is recommended to follow the documentation.
Here's a summary of some of the features that you should be aware of and external storage for use:
A. The external memory card is not ready to use at any time, so be sure to check the availability of it before use
B. The data stored on the external memory card is visible to all applications, and the user is also visible (using FileManager), so security is not very good, although the document claims to be able to write program private data on the external memory card, but it seems useless, With FileManager you can still delete or edit files (the FileManager feature on the market is powerful, allowing users to see all the files in the SD card, and the files they can see).
C. Android phone support to the external memory card mount to the PC as a U disk, when connected to the data cable, then the SD card into a USB stick connected to another operating system. What that means is that although some file attributes (hidden, private, etc.) are not necessarily useful on the PC, the user can manipulate the files on the PC (as mentioned in the 2nd).
D. If you use an external memory card to save data, be sure to do something extra: where the external memory card is not available, and how to synchronize the data when it is available (this is a more troublesome place, the possible way is when the SD card is not allowed to write data, but this user experience is not very good, but as you know, Many applications do this); Your data is corrupted. Of course, common anomalies also have to be considered, such as the space is full, unable to write, disk bad path and so on.
1.SQLite Database
Android supports the database very well, it itself integrates the SQLite database, each application can easily use it, or more specifically, Android relies entirely on the SQLite database, all of its system data and the use of structured data are stored in the database.
It has the following advantages:
A. There is no denying that efficiency is outstanding.
B. Ideal for storing structured data
C. Facilitates the transfer of data between different activity and even different applications
Previously there was an article< in-depth understanding of data transfer between activity >Talk about the hassle of transferring data between different activity and different applications, especially for large data structures, because the activity is a Java object, but it's not possible to create an instance and use it like other class objects. It is also not possible to add setters and getters to the activity (although this did not compile the error). A better solution would be to write structured data to the database and then pass their URIs between different activity.
D. dedicated contentprovider to help manage and maintain the database
E. Easy to set access rights, private or visible
F. Easy to operate, use standard crude statement, Contentresolver.query (), update (), delete () insert (), seeContentresolver
G. Good portability and versatility, crude can be achieved with standard SQL statements
It can be used to refer to the document , it is not clear here.
1.Internet Network
Network is a relatively unreliable one, because the network stability of mobile terminals, as well as the resulting traffic so that people can not hurt, users are more hurt. However, for very important real-time data, or to be sent to the remote server processing, you can also consider the use of real-time network transmission. That's a precedent, as Apple and Google do, and iphone devices and Android devices collect users ' information without their knowledge, and then send them to Apple and Google's servers without the user's knowledge, the so-called "tracking door." In addition, the smartphone (especially Android and the fiery iphone) above the application will secretly run in the background, collect user data, and then secretly send the server, the direct damage is the user traffic.
In contrast to these several ways, you can summarize the following:
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 of endless
4. Files are used to store files (i.e., non-configuration information or structured data) such as text files, binaries, PC files, multimedia files, downloaded files, etc.
5. Try not to create a file
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, not to send to the network, although you also have a lot of frustration. User also helpless, 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. Another principle is the simplest principle, which means that it can be handled in a simple way, not in a complicated way. such as storing a few data or simple objects, with sharedpreference can do, why also write a contentprovider it?

Android Development Note: A detailed description of how data is stored

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.