Data storage in Android (iii)--sqlite database storage data

Source: Internet
Author: User
Tags sqlite database

When an application is installed in Android, we generate a lot of data in the process of using the app, and the app has its own data, so how do we store the data?

How data is stored

There are 5 ways to store your Android data:

1. Sharedpreferences Storage Data
sharedpreferences data storage, also known as XML storage. This is the data stored under the "data/data/Package name/share_prefs" path to the XML file.
Related connection: "Data storage in Android (i)--sharedpreferences storage data"
2. File storage Data
divided into internal storage and external storage. Internal storage is an application that uses Android to allocate memory space for itself, and the data is stored in the appropriate file under the "/data/data/Package name/files" path. The external storage is the memory that uses the mobile phone sdcard (this sdcard is not what we often say that can disassemble the replacement SD card, that SD card we call the expansion card), use this part of memory to declare the corresponding permission.
RELATED Links: "Data storage in Android (ii)--File storage Data"
3. SQLite database stores Data
using a database for storage, this general amount of data is relatively large.
Related connection: "Data storage--sqlite Database storage Data" in Android
4. Storing data using ContentProvider
this looks familiar, ContentProvider is also one of the four components of Android. ContentProvider is generally a third party to provide data storage, to our phone contacts, photos, music, etc. ..
related connections: "Data storage--contentprovider storage data in Android "
5. Networked Storage data
This is to upload the data to the network for storage.

Let's go to our main content today and use the SQLite database to store the data.

SQLite database stores data

  SQLite is a lightweight relational database , since it is a relational database, that operation is actually similar to MySQL, SQL Server.
  The biggest difference between SQLite and other databases is support for data types , and when you create a table, you can specify the data type of a column in the CREATE TABLE statement, but you can put any data type in any column. When a value is inserted into the database, SQLite checks its type. If the type does not match the associated column, SQLite attempts to convert the value to the type of the column. If it cannot be converted, the value is stored as the type it has. For example, you can put a string into an INTEGER column. SQLite calls this a "weak type" (Manifest typing.).
To manipulate the database SQLite, we need to use the Sqliteopenhelper class to operate. The operation of the database is "add, delete, change, check". Before we learn the operation of the database, we must first learn how to create a database ...

Create a database

Database operation with the help of Sqliteopenhelper,sqliteopenhelper is an abstract class, We are going to create a mysqliteopenhelper inheriting Sqliteopenhelper class when we use Sqliteopenhelper.
Sqliteopenhelper has two very important methods: the Getreadabledatabase () method returns the database as a read-only, and the Getwriteabledatabase () method obtains a writable database object. Here we use the Getwriteabledatabase () method to obtain the database object.

Create a Mysqliteopenhelper inherited Sqliteopenhelper class:

1  Public classMysqliteopenhelperextendsSqliteopenhelper {2 3      //constructor, passing in four parameters to the context object, the database name, the cursor object that operates the database, and version number versions. 4      PublicMysqliteopenhelper (context context, String name, Sqlitedatabase.cursorfactory factory,intversion) {5         Super(context, name, Factory, version);6     }7     //Custom Constructors8      PublicMysqliteopenhelper (Context context, String name) {9          This(Context, Name,NULL, 1);//Pass in the name of the context and database, call the above constructorTen     } One  A @Override -      Public voidonCreate (sqlitedatabase sqlitedatabase) { -         //When you create a database, create a table of data tables theString sql = "CREATE table if not exists user (ID integer primary key autoincrement, name varchar (), Passwords varchar (2 0)) "; - sqlitedatabase.execsql (SQL); -  -     } + @Override -      Public voidOnupgrade (Sqlitedatabase sqlitedatabase,intIintI1) { +     //To upgrade a database, you only need to pass in a number that is larger than the one you created in the previous version when creating this class object.  A     } at}

To create a database:

1     // Create a database 2         New Mysqliteopenhelper (Getapplicationcontext (), "create_db"); // the database name is create_db.  3         sqlitedatabase db = Mysqliteopenhelper.getwritabledatabase ();

Increase

insert with sqlitedatabase (string table, String nullcolumnhack, contentvalues values) method to insert data. This method contains three parameters:  
Let's first enumerate the INSERT statement in SQLite: insert INTO user (name, Passwords)] VALUES ("Zhang San", "123456");  
String table: operation.  
String Nullcolumnhack: is used when we do not specify the addition of data, Fill in a null value for data in the data table that can add a null value. Generally this parameter we pass in NULL.  
contentvalues values: is used to pass data, usually we pass contentvalues The Putxxx () method of the object of the class encapsulates the data and then adds the data into the database.  
Contentvalues class, similar to map in Java, holds data in the form of key-value pairs.

 1  contentvalues value = new   Contentvalues ();  2  value.put ("name", "Zhang San"); //  3  value.put ("Passwords", "123456"); //  4  //  The DB database object was previously created and is used directly here.  5  db.insert ("User", null , value); Span style= "COLOR: #008000" >// 

Delete

Delete the data using Sqlitedatabase's Delete (string table, String Whereclause, string[] whereargs) method. This method consists of three parameters:
Let's start by listing a DELETE statement in SQLite: DELETE FROM user WHERE name="张三" .
String table: The name of the data table to manipulate.
String Whereclause: constrains the condition to delete rows. Equivalent to the "where name=" in the SQLite statement? Content
string[] Whereargs: The condition that corresponds to the constraint delete row for the previous parameter. Equivalent to "Zhang San" in "where Name=" Zhang San "".
Note: If the argument string whereclause and parameter string[] Whereargs are null, all rows are deleted.

    // The DB database object was previously created and is used directly here.     New string[]{"Zhang San"});

Change

Use the Sqlitedatabase update (string table, contentvalues values, String whereclause, String[] Whereargs) method to delete data. This method contains four parameters:  
Let's first list a modified statement in SQLite: UPDATE user SET name= "John Doe", passwords= "123" WHERE name= "Zhang San" .  
String table: operation.  
contentvalues values: is used to pass data, usually we pass contentvalues The Putxxx () method of the object of the class encapsulates the data and then adds the data into the database.  
String Whereclause: constraints Modify the condition of the row. Equivalent to the "where name=" in the SQLite statement? Content  
string[] Whereargs: corresponds to the criteria for the constraint delete row for the previous parameter. Equivalent to "Zhang San" in "where Name=" Zhang San "".

1         // The DB database object was previously created and is used directly here.  2         new  contentvalues (); 3         Values.put ("Passwords", "ABCD"); 4         New string[]{"Zhang San"});

Check

For the "check" operation, Sqlitedatabase provides a variety of methods.
Let's start by listing a modified statement in SQLite: SELECT passwords="123" FROM user .
(1) Query with SQL statement. Here Sqlitedatabase provides the method:

    • rawquery (String sql, string[] selectionargs): This method returns an object of the cursor class that is used to manipulate the results of the query.
1String sql = "SELECT * from User";2cursor cursor = db.rawquery (SQL,NULL);3Cursor.movetofirst ();//move to the first line of the result4          while(!Cursor.isafterlast ()) {5String name=cursor.getstring (Cursor.getcolumnindex ("name"));6String passwords=cursor.getstring (Cursor.getcolumnindex ("Passwords"));7LOG.D ("Data", "name=" + name + "password=" +passwords);8 Cursor.movetonext ();9}

(2) Using Sqlitedatabase default method query:

    • Query (string table, string[] columns, string selection, string[] Selectionargs, String groupBy, string having, string By the way, String limit): This method has more than n parameters ah ... String table is the name of the data table for the operation; string selection is the filtered field option; string[] Selectionargs is the value corresponding to the field option; String GroupBy is the grouping of filter results; string has a condition set on a group created by the GROUPBY clause; string order is the sort of result, string limit is the display limit of the filter result, for example "2, 3" 3 is displayed starting from the 2nd of the filter results.
1Cursor cursor=db.query ("User",NULL,NULL,NULL,NULL,NULL, "id desc", "2,3");//Limit statement offset, num2Cursor.movetofirst ();//move to the first line of the result3          while(!Cursor.isafterlast ()) {4String name=cursor.getstring (Cursor.getcolumnindex ("name"));5String passwords=cursor.getstring (Cursor.getcolumnindex ("Passwords"));6LOG.D ("Data", "name=" + name + "password=" +passwords);7 Cursor.movetonext ();8}

So the database operation and storage is almost, oh, for the database operation is nothing more than these four kinds of ...

Data storage in Android (iii)--sqlite database storage data

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.