Four ways to store Android data

Source: Internet
Author: User
Tags sqlite database

Clear thinking, four ways to store data from Android

As a finished application, data storage operations are essential. As a result, the Android system offers four ways to store data. are: Sharepreference, SQLite, Content provider, and file. As the Android system, the data are basically private, are stored in the "data/data/package name" directory, so to achieve data sharing, the correct way is to use the content Provider.

  SQLite: SQLite is a lightweight database that supports basic SQL syntax and is often used as a way of storing data. Android provides a class named Sqlitedatabase for this database, encapsulating some of the APIs that manipulate the database.

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

  File : the commonly used method of storing files (I/O), often storing large amounts of data, but the drawback is that updating the data will be a difficult task.

  ContentProvider: A data storage method that enables all applications to be shared in an Android system, because the data is usually private to each application, so this storage method is less used, but it is an essential storage method. For example, audio, video, pictures, and contacts can generally be stored in this way. Each content provider provides a public URI (wrapped as a URI object), and if the application has data to share, it needs to use content provider to define a URI for the data, and then the other application passes the content Provider pass in the URI to manipulate the data.

SQLite is a lightweight database for embedded device design with only five data types, namely:

Null: null value

Integer: Integers

REAL: Floating point

TEXT: String

BLOB: Big Data

In SQLite, the Boolean and date types are not specifically designed because the Boolean can replace true and false with integers 0 and 1, whereas the date type can have text, real, and integer values in a particular format instead of the display. To facilitate the operation of the date type, SQLite provides a set of functions as described in: http://www.sqlite.org/lang_datefunc.html. This simple data type design is more in line with the requirements of embedded devices. For more information about SQLite, see: http://www.sqlite.org/

The Android.database.sqlite package is available in the Android system for adding, deleting, changing, and checking SQLite databases. The main methods are as follows:

  BeginTransaction (): Start a transaction.

  Close (): Closes the connection and frees the resource.

  Delete (string table, String Whereclause, string[] whereargs): Deletes the qualifying record based on the given criteria.

  Endtransaction (): Ends a transaction.

  Execsql (String SQL): Executes the given SQL statement.

  Insert (string table, String nullcolumnhack, contentvalues values): Inserts a record according to the given criteria.

  Openorcreatedatabase (String path, Sqlitedatabase.cursorfactory Factory): The database is connected based on the given criteria and is created if the database does not exist.

Query (string table, string[] columns, string selection, string[] Selectionargs, String groupBy, String having, string Orde Rby): Executes the query.

  Rawquery (String sql, string[] Selectionargs): Executes the query based on the given SQL.

Update (string table, contentvalues values, String whereclause, string[] whereargs): Modifies a record that meets the criteria given the criteria.

In addition to the main appeal methods, Android also provides a number of practical methods, in short: In fact, Android access to the database is a very convenient thing.

First, create a database

Create a database from the Openorcreatedatabase (String path, Sqlitedatabase.cursorfactory Factory) method.     

1 Sqlitedatabase db =this.openorcreatedatabase ("Test_db.db", context.mode_private, NULL);
2 sqlitedatabase DB2 = Sqlitedatabase.openorcreatedatabase ("/data/data/com.test/databases/test_db2.db3", null);

In both ways, the database can be created, this.openorcreatedatabase is for Sqlitedatabase.openorcreatedatabase, as the code sees, the native Sqlitedatabase.openorcreatedatabase () method The first parameter requires absolute path strength, and all databases are stored in the "data/data/Application registration/databases" directory, So it is a repetitive and complicated task to enter a complete absolute path. This operation is omitted with This.openorcreatedatabase. The results after performing the operation are    as follows:

 

You can also create a database by writing a method that inherits the Sqliteopenhelper class, which is a more advanced way to create, so don't describe it here.

Second, create a data table, insert data.

The Android system does not provide a special way to create a data table, the data table is created with SQL statements, the code is as follows:

1 db.execsql ("CREATE Table tab (_id INTEGER PRIMARY KEY autoincrement, name TEXT not NULL)");

After the table is created, Insert the data via the Insert (string table, String nullcolumnhack, Contentvalues values) method, where the parameter meanings are:

Table: Target table name

Nullcolumnhack: Specifies a column column name in the table. Because in SQLite, it is not allowed to insert records where all columns are null , so the initial value has a null value , this column should be explicitly given null

The Values:contentvalues object, similar to the map in Java. Saves data in a key-value pair.

The data insertion code is as follows: 

1 contentvalues values =new contentvalues ();
2 for (int i=0;i<10;i++) {
3 values.put ("name", "test" + i);
4 Db.insert ("tab", "_id", values);
5 }

After doing this, a data table called "tab" is added, which makes it easy to view this table structure and data with the SQLite client (recommended: SQLite Expert Personal 3). Such as:

  

Third, modify the data

The update (string table, contentvalues values, String whereclause, string[] Whereargs) method is used to modify the data, and its four parameters have the following specific meanings:

Table: Target table name

Values: The new value to be modified

The Whereclause:where clause, excluding the remainder of the WHERE keyword, which can be taken with? Placeholder. Null if there is no clause.

Whereargs: Used to replace the Whereclause parameter? The parameters of the placeholder. NULL if no incoming parameter is required.

The data modification code is as follows:

1 contentvalues values =new contentvalues ();
2 values.put ("name", "name");
3 Db.update ("tab", Values, "_id=1", null);
4 db.update ("tab", Values, "_id=", New string[]{"5"});

Execution results such as _id=1 and _id=5 data, the value of the Name field is modified for "name".

Iv. querying data.

Previously, using the SQLite client to view data, use the query () and Rowquery () methods provided by Android to execute queries. The specific code is as follows:  

1 Cursor C = db.query ("tab", NULL, NULL, NULL, NULL, NULL, NULL);
2 C.movetofirst ();
3 while (!c.isafterlast ()) {
4 int index = C.GETCOLUMNINDEX ("name");
5 log.d ("SQLite", C.getstring (index));
6 C.movetonext ();
7}
8 C = db.rawquery ("Select * from tab", NULL);
9 C.movetofirst ();
Ten while (!c.isafterlast ()) {
int index = c.getcolumnindex ("name");
log.d ("SQLite", C.getstring (index));
C.movetonext ();
14}

Query results such as:

Can be clear in the query results, the red line up and down the data is exactly the same, that is, the query and Rawquery method in the difference is only the difference in the required parameters. The Rawquery method requires developers to write query SQL manually, and the query method consists of a SQL statement composed of a number of clauses, such as the target table name, the WHERE clause, the ORDER BY clause, the HAVING clause, and so on. The two methods return the cursor object, so the two sides in the use of the better or worse, to see the specific situation. I prefer the rawquery approach, because this approach is closer to traditional Java development, and can also be written by a professional DBA to write SQL statements, which is more consistent with the idea of MVC, and this code is more readable. (There are too many parameters in the query method, a little memory of who is the ORDER BY clause, who is the HAVING clause)

The cursor object can be understood as a cursor object, anyone who knows something about the data, believe that this object is not unfamiliar, where the machine is no longer described. It is only a reminder that when you first read the data in a cursor object, you must move the cursor first, or the position of the cursor will throw an exception before the first record.

V. Deletion of data

Deleting the data is also a simple matter, just call the Delete method, pass in the parameters,Delete (string table, String Whereclause, string[] whereargs) parameter three parameters specific meaning is as follows:

Table: Target table name

The Whereclause:where clause, excluding the remainder of the WHERE keyword, which can be taken with? Placeholder. Null if there is no clause.

Whereargs: Used to replace the Whereclause parameter? The parameters of the placeholder. NULL if no incoming parameter is required.

The specific code is as follows:

Db.delete ("tab", "_id=?") Or Name=? ", New string[]{" 8 "," Name "});

The results of the implementation are as follows:

The data for _id=8 and name= ' name ' are all deleted.

The crud operation for the entire database has been demonstrated. Finally, be sure to remember to call the close () method to close the connection and release the resource after you have finished manipulating the data. This is the reason I believe that we all understand.

sharedpreferences is also a lightweight method of data storage, which is essentially based on XML files that store Key-value key-value pairs of data, typically used to store some simple configuration information. Its storage location is under the/data/data/< package name >/shared_prefs directory. The Sharedpreferences object itself can only fetch data without supporting storage and modification, and storage modifications are implemented through the editor object. The steps to implement Sharedpreferences storage are as follows:

First, according to the context to obtain Sharedpreferences object

Second, use the edit () method to get the editor object.

Third, through the editor object store Key-value key value pair data.

Iv. submit data through the commit () method.

The specific implementation code is as follows:

1 Publicclass mainactivity extends Activity {
2 @Override
3 publicvoid onCreate (Bundle savedinstancestate) {
4 super.oncreate (savedinstancestate);
5 Setcontentview (R.layout.main);
6
7//Get Sharedpreferences Object
8 Context ctx = mainactivity.this;
9 Sharedpreferences sp = ctx.getsharedpreferences ("sp", mode_private);
10//Deposit data
Editor editor = Sp.edit ();
editor.putstring ("String_key", "STRING");
editor.putint ("Int_key", 0);
Editor.putboolean ("Boolean_key", true);
Editor.commit ();
16
17//return value of String_key
log.d ("SP", Sp.getstring ("String_key", "none"));
19//If Not_exist does not exist, the return value is "none"
log.d ("SP", Sp.getstring ("Not_exist", "none"));
+ }
22}

After this code is executed, a sp.xml file is generated in the/data/data/com.test/shared_prefs directory, and an application can create multiple such XML files. :

The specific contents of the Sp.xml file are as follows:

1 <?xml version= ' 1.0 ' encoding= ' utf-8 ' standalone= ' yes '?>
2 <map>
3 <string name= "String_key" >string</string>
4 <int name= "Int_key" value= "0"/>
5 <boolean name= "Boolean_key" value= "true"/>
6 </map>

In the program code, through the GetXXX method, you can easily get the value of the corresponding key, if the key value is wrong or the key has no corresponding value, Sharedpreferences provides an opportunity to give the default value, in order to ensure the robustness of the program. As the result of the operation, because there is no value of "not_exist" key, so log prints its default value: "None". There is no exception thrown in the process of accessing a key value that does not exist.

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.

ContentProvider is a mechanism for data sharing among different applications in the Android platform. An application can use this mechanism if it needs to allow other programs to manipulate its own data. And this approach ignores the underlying data storage implementations, ContentProvider provides a uniform way to implement data manipulation through URIs. The steps are:

1. Define a ContentProvider in the current application.

2. Register this contentprovider in the androidmanifest.xml of the current application

3. Other applications obtain this ContentProvider data through Contentresolver and URIs.

Contentresolver provides methods such as insert (), delete (), query (), and update (). Used to implement access to data in the ContentProvider.

A URI is a generic resource marker that divides it into a,b,c,d 4 parts:

A: Standard prefixes that cannot be changed, including; "content://", "tel://" and so on. When the current prefix is "content://", the description controls the data through a content provider

The identity of the B:uri, which is declared by the authorities property, which defines which ContentProvider provides the data. For third-party applications, to guarantee the uniqueness of the URI identity, it must be a complete, lowercase class name. For example, " Content://com.test.data.myprovider "

C: The path, which can be approximated as the name of the table in the database that needs to be manipulated, such as: "Content://hx.android.text.myprovider/name"

D: If the URI contains an ID that represents the record that needs to be fetched, then the data corresponding to that ID is returned, and if there is no ID, it returns all;

Here's a sample code that shows how to get data from one application to another.

In application A, inherit the Contprovider class and override the method.

1 Publicclass MyProvider extends contentprovider{
2 @Override
3 publicint Delete (Uri Uri, String selection, string[] Selectionargs) {
4//TODO auto-generated method stub
5 Return0;
6}
7
8 @Override
9 public String GetType (Uri uri) {
Ten//TODO auto-generated method stub
One by one returnnull;
12}
13
@Override
Public URI insert (URI uri, contentvalues values) {
Returnnull;
17}
18
19//Initialize a database in Create
@Override
Publicboolean OnCreate () {
Sqlitedatabase db =this.getcontext (). Openorcreatedatabase ("Test_db.db3", context.mode_private, NULL);
Db.execsql ("CREATE Table tab (_id INTEGER PRIMARY KEY autoincrement, name TEXT not NULL)");
Contentvalues values =new contentvalues ();
Values.put ("name", "Test");
Db.insert ("tab", "_id", values);
Db.close ();
Returntrue;
29}
30
31//Implement the Query method
@Override
Public Cursor query (URI uri, string[] projection, String selection,
String[] Selectionargs, String sortOrder) {
Sqlitedatabase db =this.getcontext (). Openorcreatedatabase ("Test_db.db3", context.mode_private, NULL);
Cursor C = db.query ("tab", NULL, NULL, NULL, NULL, null,null);
PNS return C;
38}
39
@Override
Publicint update (URI Uri, contentvalues values, String selection,
String[] Selectionargs) {
+//TODO auto-generated method stub
Return0;
45}
46}

This contentprovider is declared in its androidmanifest.xml, where the authorities property defines the URI identifier for this contentprovider.

<provider android:name= ". MyProvider "android:authorities=" Com.test.MyProvider "/>

In application B, get the data in program A's ContentProvider by Contentresolver.

1 Publicclass mainactivity extends Activity {
2 @Override
3 publicvoid onCreate (Bundle savedinstancestate) {
4 super.oncreate (savedinstancestate);
5 Setcontentview (R.layout.main);
6
7//Get context
8 Context ctx = mainactivity.this;
9//Get Contentresolver Object
Ten Contentresolver resolver = Ctx.getcontentresolver ();
11//Get URI Object
uri uri = uri.parse ("Content://com.test.myprovider");
13//Get Data
the Cursor c = resolver.query (URI, NULL, NULL, NULL, NULL);
C.movetofirst ();
(int i=0; I<c.getcount (); i++) {
+ int index = c.getcolumnindexorthrow ("name");
String src = c.getstring (index);
log.d ("", SRC);
C.movetonext ();
+ }
+ }
23}

The results of application B are as follows, and we can see from the diagram that we successfully obtained the data in program A in program B:

Look at the structure of the two applications, for example, where the red box is the program structure of application A, you can clearly see that it has a database named "Test_db.db3", the Blue box is the program structure of application B, and there is no database for storing data. From this diagram, you can determine that the result of the data queried in application B is from application A.

The above is the use of ContentProvider, this storage method compared to SQLite and sharedpreferences, its complexity is obvious, but in everywhere "cloud" today, The need for data interaction between programs makes the ContentProvider storage mechanism an essential part.

Four ways to store Android 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.