This article describes five ways to store data on the Android platform, as follows:
1 Storing data using sharedpreferences
2 File Store data
3 SQLite database stores data
4 Storing data using ContentProvider
5 Networked Storage data
Here is a detailed explanation of the characteristics of these five ways
First: Use Sharedpreferences to store data
Scope of application : save a small amount of data, and the format of the data is very simple: string type, basic type of value. such as the application of various configuration information (such as whether to open the sound effects, whether to use vibration effects, game players points, etc.), unlock password password, etc.
Core principle : save key-value Key-value pairs of data based on XML file storage, usually used to store some simple configuration information.
With Ddms's File Explorer panel, it is clear that sharedpreferences data is always stored in the/data/data/<package name>/ The Shared_prefs directory.
the Sharedpreferences object itself can only fetch data without supporting storage and modification, and storage modifications are through sharedpreferences. Edit () Gets the internal interface eDitor object implementation. the sharedpreferences itself is an interface, and the program cannot create the sharedpreferences instance directly, only through the get Shar provided by the context Edpreferences(String name, int mode) method to get the sharedpreferences instance, in which name represents the XML file name to manipulate, the second parameter is as follows:
context.mode_private: Specifies that the sharedpreferences data can only be read and written by the application.
context.mode_world_readable: Specifies that the sharedpreferences data can be read by other applications , but cannot be written.
context.mode_world_writeable: Specifies that the sharedpreferences data can be read by other applications, write
Editor has the following main important methods:
Sharedpreferences.editor Clear (): empties all data in Sharedpreferences
sharedpreferences.editor putxxx (String key, xxx value): the data corresponding to the specified key is deposited to sharedpreferences, where xxx can be a Boolean, Float,int and other basic types of data
sharedpreferences.editor Remove (): deletes the data item for the specified key in the Sharedpreferences
Boolean commit (): when editor is finished editing, use this method to commit the modification
Actual case: The operating interface is as follows
Here are only two buttons and an input text box, layout is simple, so this does not give the interface layout file, the program core code is as follows:
classViewoclImplementsview.onclicklistener{@Override Public voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.btnset://Step 1: Get input valuesString Code =Txtcode.gettext (). toString (). Trim (); //Step 2-1: Create a Sharedpreferences.editor interface object, lock represents the XML file name to write, mode_world_writeable write operationSharedpreferences.editor Editor = getsharedpreferences ("Lock", mode_world_writeable). Edit (); //Step 2-2: Put the retrieved value into the fileEditor.putstring ("Code", code); //Step 3: SubmitEditor.commit (); Toast.maketext (Getapplicationcontext (),"Password Setup succeeded", Toast.length_long). Show (); Break; CaseR.id.btnget://Step 1: Create a Sharedpreferences interface objectSharedpreferences read = Getsharedpreferences ("Lock", mode_world_readable); //Step 2: Get the values in the fileString value = read.getstring ("code", "" "); Toast.maketext (Getapplicationcontext (),"Password is:" +value, Toast.length_long). Show (); Break; } } }
Read and write sharedpreferences for other applications: steps below
1, when creating Sharedpreferences, specify the mode_world_readable mode, indicating that the sharedpreferences data can be read by other programs
2. Create the corresponding context for other applications:
Context Pvcount = Createpackagecontext ("Com.tony.app", context.context_ignore_security); The Com.tony.app here is the package name of the other program.
3, use the context of other programs to obtain the corresponding sharedpreferences
Sharedpreferences read = Pvcount. Getsharedpreferences ("lock", context.mode_world_readable);
4, if the data is written, use the editor interface, all other operations are consistent with the previous.
Compared with SQLite database, Sharedpreferences object is more convenient and concise than creating database, creating table, writing SQL statement and so on. But Sharedpreferences also has its own flaws, such as its functional storage boolean,int,float,long and string five of simple data types, such as its inability to perform conditional queries. So no matter how simple the sharedpreferences data store operation is, it can only be a supplement to the storage method, and it cannot completely replace other data storage methods such as SQLite database.
The second type: file storage data
Core principle: The context provides two ways to open the file IO stream in the data file FileInputStream openfileinput (String name); FileOutputStream (String name, int mode), the first parameter of the two methods is used to specify the file name, and the second parameter specifies the mode in which the files are opened. The following values are optional:
mode_private: As the default mode of operation, which means that the file is private data and can only be accessed by the app itself, in which the content of the write overwrites the contents of the original file, if you want to append the newly written content to the original file. You can use Context.mode_append
mode_append: The mode checks whether the file exists, appends content to the file, or creates a new file.
mode_world_readable: Indicates that the current file can be read by another application;
mode_world_writeable: Indicates that the current file can be written by another application.
In addition to this, the context also provides several important methods:
Getdir (String name, int mode): Gets or creates a subdirectory of name in the application's Data folder
File Getfilesdir (): Gets the absolute path to the application's Data folder
String[] FileList (): Returns all files for the app Data folder
Actual Case: interface continuation
The core code is as follows:
PublicString Read () {Try{FileInputStream instream= This. Openfileinput ("Message.txt"); byte[] buffer =New byte[1024]; intHasread = 0; StringBuilder SB=NewStringBuilder (); while((Hasread = instream.read (buffer))! =-1) {sb.append (NewString (buffer, 0, Hasread)); } instream.close (); returnsb.tostring (); } Catch(Exception e) {e.printstacktrace (); } return NULL; } Public voidWrite (String msg) {//Step 1: Get input values if(msg = =NULL)return; Try { //Step 2: Create a FileOutputStream object, mode_append Append modeFileOutputStream fos = openfileoutput ("Message.txt", Mode_append); //Step 3: Put the retrieved value into the fileFos.write (Msg.getbytes ()); //Step 4: Turn off Data flowFos.close (); } Catch(Exception e) {e.printstacktrace (); } }
the first parameter of the Openfileoutput () method specifies the file name, cannot contain the path delimiter "/", and if the file does not exist, Android automatically creates it. the created file is saved in the/data/data/<package Name>/files directory, such as:/DATA/DATA/CN.Tony.app/files/Message.txt,