[Android] Data Storage Methods

Source: Internet
Author: User
Tags map data structure

As a complete application, data storage operations are essential. Therefore, the android system provides four data storage methods. They are sharepreference, SQLite, content provider, and file. In Android, data is basically private and stored in the "Data/data/package name" directory. Therefore, to share data, use the content provider

ADB shell // enter the emulator Environment

CD/data/Data

Ls


SQLite:SQLite is a lightweight database that supports basic SQL syntax and is a common data storage method. Android provides a class named sqlitedatabase for this database, which encapsulates APIs for database operations.

  Sharedpreference:In addition to the SQLite database, another common data storage method is essentially an XML file, which is often used to store simple parameter settings.

  File:That is to say, the file (I/O) storage method is often used to store a large amount of data, but the disadvantage is that updating data will be difficult.

  Contentprovider:A data storage method that can be shared by all applications in the Android system. Because data is usually private among applications, this storage method is rarely used, however, it is an essential storage method. For example, audio, video, image, and address book can be stored in this way. Each content provider provides a public uri (encapsulated as a URI object). If the application needs to share data, the content provider needs to define a URI for the data, then other applications use the content
The URI passed in by the provider to operate the data.


I. Use sharedpreferences to store data


First, describe the sharedpreferences storage method. It is a mechanism provided by Android to store some simple configuration information, such as the username and password of the login user. It uses the map data structure to store data, and stores data in key-value mode, which can be simply read and written. The specific example is as follows:

Package tianshuai. androidsharedpreferences; import android. app. activity; import android. content. context; import android. content. sharedpreferences; import android. content. sharedpreferences. editor; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; import android. widget. toast; public class androidsharedpreferences extends activity {Private Static final string tag = "androidsharedpreferences"; private edittext etname; private edittext etage;/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); button btset = (button) This. findviewbyid (R. id. bt_set); button btread = (button) This. findviewbyid (R. id. bt_read); etname = (edittext) This. findviewbyid (R. id. et_name); etage = (edittext) This. findviewbyid (R. id. et_age); btset. setonclicklistener (New onclicklistener () {@ override public void onclick (view v) {// obtain the name and age string name = etname. gettext (). tostring (); string age = etage. gettext (). tostring (); // create sharedpreferences sp = getsharedpreferences ("Preferences", context. mode_private); // Add data editor = sp. edit (); Editor. putstring ("name", name); Editor. putint ("Age", integer. parseint (AGE); // Save the data if (editor. commit () toast. maketext (androidsharedpreferences. this, R. string. save_success, 1 ). show (); else toast. maketext (androidsharedpreferences. this, R. string. save_failed, 1 ). show () ;}}); btread. setonclicklistener (New onclicklistener () {@ override public void onclick (view v) {// create sharedpreferences sp = getsharedpreferences ("Preferences", context. mode_private); // obtain the data string name = sp. getstring ("name", "defname"); string age = sp. getint ("Age", 0) + "; // display the data etname. settext (name); etage. settext (AGE );}});}}

Main. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent"> <! -- Name --> <relativelayout Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"> <textview Android: layout_width = "70dip" Android: layout_height = "wrap_content" Android: textsize = "25dip" Android: Id = "@ + ID/TV _name" Android: text = "@ string/TV _name"/> <edittext Android: layout_width = "300dip" Android: layout_height = "wrap_content" Android: layout_torightof = "@ ID/TV _name" Android: Id = "@ + ID/et_name" /> </Relativelayout> <! -- Age --> <relativelayout Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"> <textview Android: layout_width = "70dip" Android: layout_height = "wrap_content" Android: textsize = "25dip" Android: Id = "@ + ID/TV _age" Android: text = "@ string/TV _age"/> <edittext Android: layout_width = "300dip" Android: layout_height = "wrap_content" Android: layout_torightof = "@ ID/TV _age" Android: Id = "@ + ID/et_age"/> </Relativelayout> <! -- Button --> <relativelayout Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: gravity = "right"> <button Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: text = "@ string/bt_write" Android: Id = "@ + ID/bt_set"/> <button Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_torightof = "@ ID/bt_set" Android: text = "@ string/bt_read" Android: id = "@ + ID/bt_read"/> </relativelayout> </linearlayout>

Strings. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Resources> <string name = "hello"> Hello world, androidsharedpreferences! </String> <string name = "app_name"> Android Application configuration </string> <string name = "TV _name"> name </string> <string name = "TV _age"> age </string> <string name = "bt_write"> Settings </string> <string name = "bt_read"> Read </string> <string name = "save_success"> saved successfully </string> <string name = "save_failed"> failed to save </string> </resources>

We use "/data/COM. Changcheng. sharedpreferences/shared_prefs/preferences. xml ". Export preferences. XML to view the following content:

ADB pull/data/COM. Changcheng. sharedpreferences/shared_prefs/preferences. xml/usr/AA

<? XML version = '1. 0' encoding = 'utf-8' standalone = 'Yes'?> <Map> <string name = "name"> Great Wall </string> <int name = "Age" value = "25"/> </map>

Key code:

void    WriteSharedPreferences(String strName,String strPassword){      SharedPreferences user = getSharedPreferences(“user_info”,0);      uer.edit();      user.putString(“NAME”,strName);      user.putString(“PASSWORD”,strPassword);      user.commit();}void   ReadSharedPreferences(){      StringstrName,strPassword;      SharedPreferences user = getSharedPreferences(“user_info”,0);      strName= user.getString(“NAME”,””);      strPassword= user getString(“PASSWORD”,””);}

The Data Reading and writing methods are very simple, but there are some differences when writing: First call edit () to make it edit, then you can modify the data, and finally use commit () submit the modified data. In fact, sharedpreferences stores data to the device in XML format, under/data/<packagename>/shares_prefs in fileexplorer of ddms. Sharedpreferences is restricted: it can only be used in the same package and cannot be used between different packages.


Ii. File Storage Data

The file storage method is a commonly used method. The method for reading/writing files in Android is exactly the same as that in Java for implementing I/O. It provides openfileinput () and openfileoutput () to read files on the device. The specific example is as follows:

Stringfn = "moandroid. log ";
Fileinputstreamfcm = openfileinput (FN );
Fileoutputstreamfos = openfileoutput (FN, context. mode_private );
Detailed operation see blog: http://blog.csdn.net/tianshuai11/article/details/7426340

Iii. SQLite


Detailed operation see blog: http://blog.csdn.net/tianshuai11/article/details/7435501
Iv. contentprovider

1) contentprovider Introduction

When an application inherits the contentprovider class and overwrites the class to provide and store data, it can share its data with other applications. Although data can be shared externally by using other methods, the data access method varies depending on the data storage method. For example, if data is shared externally by using the file method, you need to perform file operations to read and write data; sharedpreferences is used to share data. You must use the sharedpreferencesapi to read and write data. The advantage of using contentprovider to share data is to unify the data access mode.

2) URI class Introduction

Uri indicates the data to be operated. Uri contains two parts: 1. contentprovider, 2. a URI consists of the following parts:

1> scheme: the content provider's scheme has been defined by android as: Content ://...

2> Host Name (or authority): Used to uniquely identify the contentprovider, which can be found by external callers.

3> path: it can be used to represent the data to be operated. The path construction should be based on the business, as shown below:

To operate records with the ID of 10 in the contact table, you can build the following path:/contact/10.

Name field of the record whose ID is 10 in the contact table, contact/10/Name

To operate all records in the contact table, you can build the path:/contact?

The data to be operated may not necessarily come from the database or be stored in files, as follows:

To operate the Name node under the contact node in the XML file, you can build the path:/contact/Name

To convert a string to a URI, you can use the parse () method in the URI class as follows:

Uri uri = URI. parse ("content: // com. Changcheng. provider. contactprovider/contact ")

3) Introduction to urimatcher, contenturist, and contentresolver

Because URI represents the data to be operated, we often need to parse the URI and obtain data from the URI. The Android system provides two tool classes for Uri operations: urimatcher and contenturis. Understanding their usage will facilitate our development work.

Urimatcher: Used to match a URI. Its usage is as follows:

1> first, register all the URI paths you need to match, as shown below:

Urimatcher = new urimatcher (urimatcher. no_match); // constant urimatcher. no_match indicates the return code (-1) that does not match any path ).

// If the match () method matches the content: // com. Changcheng. SQLite. provider. contactprovider/contact path, 1 is returned.

Urimatcher. adduri ("com. Changcheng. SQLite. provider. contactprovider", "contact", 1); // Add a URI that needs to be matched. If yes, a matching code is returned.

// If the match () method matches the content: // com. Changcheng. SQLite. provider. contactprovider/contact/230 path, the matching code is 2.

Urimatcher. adduri ("com. Changcheng. SQLite. provider. contactprovider", "contact/#", 2); // # It is a wildcard

2> after registering the URI to be matched, you can use urimatcher. the match (URI) method matches the input URI. If it matches, the matching code is returned. The matching code is the third parameter passed in by calling the adduri () method. Assume that it matches the content: // COM. changcheng. SQLite. provider. contactprovider/contact path. The returned matching code is 1.

Contenturis: used to obtain the ID part after the URI path. It has two practical methods:

Withappendedid (Uri, ID) is used to add the ID part to the path.

The parseid (URI) method is used to obtain the ID part from the path.

Contentresolver: When an external application needs to add, delete, modify, and query data in contentprovider, you can use the contentresolver class to obtain the contentresolver object, you can use the getcontentresolver () method provided by activity. Contentresolver uses insert, delete, update, and query methods to operate data.

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.