Highlights of data storage technology for Android

Source: Internet
Author: User

For the source code running, see the end of the article.


This article mainly introduces five data storage methods in Android.

Data storage is most frequently used during development. Here we mainly introduce five Data Storage Methods on the Android platform:

1. Use SharedPreferences to store data

2. File Storage Data

3 SQLite Database Data Storage

4. Use ContentProvider to store data

5 Network Storage Data

 

First: Use SharedPreferences to store data

SharedPreferences is a lightweight storage class on the Android platform. It mainly stores some common configurations, such as window status. Generally, reload the window status onSaveInstanceState in the Activity and save it using SharedPreferences, it provides the storage of Long integer, Int integer, and String types on the Android platform.

 

SharedPreferences is similar to the ini configuration file on Windows in the past, but it has multiple permissions:

● MODE_PRIVATE PRIVATE: the new content overwrites the original content.

● MODE_APPEND the new content to the original content

● MODE_WORLD_READABLE global read, allowing other applications to read

● MODE_WORLD_WRITEABLE: Global write, allow other applications to write, will overwrite the original data

 

In the end, it is stored in xml format. The overall efficiency is not very high. It is much better than SQLite for the conventional lightweight model. If the storage is really small, you can consider defining the file format yourself. During xml processing, Dalvik will parse the local XML Parser that comes with the underlying layer, such as the XMLpull method, so that the memory resource usage is better.

 

In essence, it stores key-value pair data based on XML files and is usually used to store some simple configuration information.

Its storage location is in the/data/<package name>/shared_prefs directory.

The SharedPreferences object can only obtain data, but does not support storage and modification. The storage modification is implemented through the Editor object.

To store SharedPreferences, follow these steps:

1. Get the SharedPreferences object based on Context

2. Use the edit () method to obtain the Editor object.

3. Use the Editor object to store key-value pairs.

4. submit data using the commit () or apply () method.

 

The following is the sample code:


[Java]
Public class MainActivity extends Activity {
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
// Obtain the SharedPreferences object
Context ctx = MainActivity. this;
SharedPreferences sp = ctx. getSharedPreferences ("SP", MODE_PRIVATE );
// Store data
Editor editor = sp. edit ();
Editor. putString ("STRING_KEY", "string ");
Editor. putInt ("INT_KEY", 0 );
Editor. putBoolean ("BOOLEAN_KEY", true );
Editor. commit ();
// Returns the STRING_KEY value.
Log. d ("SP", sp. getString ("STRING_KEY", "none "));
// If NOT_EXIST does not exist, the returned value is "none"
Log. d ("SP", sp. getString ("NOT_EXIST", "none "));
}
}

Public class MainActivity extends Activity {
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
// Obtain the SharedPreferences object
Context ctx = MainActivity. this;
SharedPreferences sp = ctx. getSharedPreferences ("SP", MODE_PRIVATE );
// Store data
Editor editor = sp. edit ();
Editor. putString ("STRING_KEY", "string ");
Editor. putInt ("INT_KEY", 0 );
Editor. putBoolean ("BOOLEAN_KEY", true );
Editor. commit ();
// Returns the STRING_KEY value.
Log. d ("SP", sp. getString ("STRING_KEY", "none "));
// If NOT_EXIST does not exist, the returned value is "none"
Log. d ("SP", sp. getString ("NOT_EXIST", "none "));
}
}

 

After the code is executed, an SP. xml file is generated under the/data/com. test/shared_prefs directory. An application can create multiple such xml files.

Compared with SQLite databases, SharedPreferences removes the need to create databases, create tables, write SQL statements, and perform other operations, making SharedPreferences more convenient and concise. However, SharedPreferences also has its own defects, such as its function storage boolean, int, float, long, and String simple data types, such as its inability to perform conditional queries. Therefore, no matter how simple the SharedPreferences data storage operation is, it can only be a supplement to the storage method, and cannot completely replace other data storage methods such as SQLite database.

 

Type 2: file storage data

Activity provides the openFileOutput () method for outputting data to a file. The specific implementation process is the same as saving data to a file in J2SE environment.

Files can be used to store a large amount of data, such as text, images, and audio.

Default location:/data/<package>/files /***.***.


[Java]
Public void save (){
Try {
FileOutputStream outStream = this. openFileOutput ("a.txt", Context. MODE_WORLD_READABLE );
OutStream. write (text. getText (). toString (). getBytes ());
OutStream. close ();
Toast. makeText (MyActivity. this, "Saved", Toast. LENGTH_LONG). show ();
} Catch (FileNotFoundException e ){
Return;
}
Catch (IOException e ){
Return;
}
}

Public void save (){
Try {
FileOutputStream outStream = this. openFileOutput ("a.txt", Context. MODE_WORLD_READABLE );
OutStream. write (text. getText (). toString (). getBytes ());
OutStream. close ();
Toast. makeText (MyActivity. this, "Saved", Toast. LENGTH_LONG). show ();
} Catch (FileNotFoundException e ){
Return;
}
Catch (IOException e ){
Return;
}
}

 

The first parameter of the openFileOutput () method is used to specify the file name. It cannot contain the path separator "/". If the file does not exist, Android will automatically create it.

The created file is saved in the/data/<packagename>/files directory, for example,/data/cn. itcast. action/files/itcast.txt, click "Window"-"ShowView"-"Other" in the Eclipse menu, expand the android folder in the dialog box, and select the File Explorer view below, expand the/data/<package name>/files directory in the File Explorer view to view the File.

 

The second parameter of the openFileOutput () method is used to specify the operation mode. There are four modes:

Context. MODE_PRIVATE = 0

Context. MODE_APPEND = 32768

Context. MODE_WORLD_READABLE = 1

Context. MODE_WORLD_WRITEABLE = 2

Context. MODE_PRIVATE: the default operation mode. This mode indicates that the file is private data and can only be accessed by the application itself. In this mode, the written content will overwrite the content of the original file, if you want to append the newly written content to the original file. You can use Context. MODE_APPEND.

Context. MODE_APPEND: the mode checks whether the file exists and appends the content to the file if it exists. Otherwise, a new file is created.

Context. MODE_WORLD_READABLE and Context. MODE_WORLD_WRITEABLE are used to control whether other applications have the permission to read and write the file.

MODE_WORLD_READABLE: indicates that the current file can be read by other applications;

MODE_WORLD_WRITEABLE: indicates that the current file can be written by other applications.

 

If you want the file to be read and written by other applications, You can input: openFileOutput ("itcast.txt", Context. MODE_WORLD_READABLE + Context. MODE_WORLD_WRITEABLE); androidhas a set of security models. When the application (.apk) is installed, the system will assign a userid to the application. When the application wants to access other resources, such as files, userid matching is required. By default, files created by any application, sharedpreferences, and databases, should be private (in/data/<package name>/files), and cannot be accessed by other programs.

Unless Context. MODE_WORLD_READABLE or Context. MODE_WORLD_WRITEABLE is specified during creation, only other programs can access it correctly.

Example of reading a file:

[Java]
Public void load ()
{
Try {
FileInputStream inStream = this. openFileInput ("a.txt ");
ByteArrayOutputStream stream = new ByteArrayOutputStream ();
Byte [] buffer = new byte [1024];
Int length =-1;
While (length = inStream. read (buffer ))! =-1 ){
Stream. write (buffer, 0, length );
}
Stream. close ();
InStream. close ();
Text. setText (stream. toString ());
Toast. makeText (MyActivity. this, "Loaded", Toast. LENGTH_LONG). show ();
} Catch (FileNotFoundException e ){
E. printStackTrace ();
}
Catch (IOException e ){
Return;
}
}

Public void load ()
{
Try {
FileInputStream inStream = this. openFileInput ("a.txt ");
ByteArrayOutputStream stream = new ByteArrayOutputStream ();
Byte [] buffer = new byte [1024];
Int length =-1;
While (length = inStream. read (buffer ))! =-1 ){
Stream. write (buffer, 0, length );
}
Stream. close ();
InStream. close ();
Text. setText (stream. toString ());
Toast. makeText (MyActivity. this, "Loaded", Toast. LENGTH_LONG). show ();
} Catch (FileNotFoundException e ){
E. printStackTrace ();
}
Catch (IOException e ){
Return;
}
}


Only applications that create a private file can access the file. If you want the file to be read and written by other applications, you can specify the Context. MODE_WORLD_READABLE and Context. MODE_WORLD_WRITEABLE permissions when creating the file.

 

Activity also provides the getCacheDir () and getFilesDir () Methods: getCacheDir () methods for obtaining/data/<package name>/cache directory getFilesDir () to obtain the/data/<packagename>/files directory.

Save the file to SDCard:

Use the openFileOutput () method of Activity to save files. The files are stored in the mobile phone space. Generally, the mobile phone storage space is not very large, and it is okay to store some small files, it is not feasible to store large files such as videos. For large files like videos, we can store them in SDCard.

What does SDCard do? You can think of it as a mobile hard disk or a USB flash disk. To use SDCard in the simulator, You need to first create an SDCard (of course, not a real SDCard, but an image file ).

 

You can create SDCard along with the simulator created in Eclipse, or you can use the doscommand to create it. In the Dos window, enter the tools directory of the android SDK installation path, run the following command to create an SDCard with a capacity of 2 GB. The file suffix can be obtained at will. img: mksdcard 2048 m d: \ AndroidTool \ sdcard. when img accesses SDCard in a program, you need to apply for the permission to access SDCard.

 

The permission to access SDCard in AndroidManifest. xml is as follows:


[Html]
<! -- Create and delete file permissions in SDCard -->
<Uses-permission android: name = "android. permission. MOUNT_UNMOUNT_FILESYSTEMS"/>

<! -- Write data to SDCard -->
<Uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/>

<! -- Create and delete file permissions in SDCard -->
<Uses-permission android: name = "android. permission. MOUNT_UNMOUNT_FILESYSTEMS"/>
 
<! -- Write data to SDCard -->
<Uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/>

[Java]
If (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED )){
File sdCardDir = Environment. getExternalStorageDirectory (); // get the SDCard directory
File saveFile = new File (sdCardDir, cmda.txt ");
FileOutputStream outStream = new FileOutputStream (saveFile );
OutStream. write ("test". getBytes ());
OutStream. close ();
}

If (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED )){
File sdCardDir = Environment. getExternalStorageDirectory (); // get the SDCard directory
File saveFile = new File (sdCardDir, cmda.txt ");
FileOutputStream outStream = new FileOutputStream (saveFile );
OutStream. write ("test". getBytes ());
OutStream. close ();
}

 

The Environment. getExternalStorageState () method is used to obtain the SDCard status. If the mobile phone has an SDCard and can be read and written, the returned state is Environment. MEDIA_MOUNTED.

The Environment. getExternalStorageDirectory () method is used to obtain the SDCard directory. To obtain the SDCard directory, you can also write:

[Java]
File sdCardDir = new File ("/sdcard"); // get the SDCard directory
File saveFile = new File (sdCardDir, "itcast.txt ");
// The above two codes can be combined into one sentence:
File saveFile = new File ("/sdcard/a.txt ");
FileOutputStream outStream = new FileOutputStream (saveFile );
OutStream. write ("test". getBytes ());
OutStream. close ();

File sdCardDir = new File ("/sdcard"); // get the SDCard directory
File saveFile = new File (sdCardDir, "itcast.txt ");
// The above two codes can be combined into one sentence:
File saveFile = new File ("/sdcard/a.txt ");
FileOutputStream outStream = new FileOutputStream (saveFile );
OutStream. write ("test". getBytes ());
OutStream. close ();


Third: SQLite Database Data Storage

SQLite is a lightweight embedded database engine that supports the SQL language and has good performance with only a small amount of memory. In addition, it is open-source and can be used by anyone. Many open-source projects (Mozilla, PHP, Python) Use SQLite. SQLite consist of the following components: SQL Compiler, kernel, backend, and attachment. SQLite makes debugging, modification, and expansion of SQLite kernel more convenient by using virtual machines and virtual database engine (VDBE.

 

Features:

For devices with limited resources,

No server process,

All data is stored in the same file across platforms,

Free replication.


 

 

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.