Data storage in Android (iii) -- data stored in SQLite database, androidsqlite

Source: Internet
Author: User

Data storage in Android (iii) -- data stored in SQLite database, androidsqlite

After an application is installed in Android, We will generate a lot of data when using the application. The application has its own data. How should we store the data?

Data Storage Methods

Android data is stored in five ways:

1. SharedPreferences Storage Data 
SharedPreferences is also called xml storage. This is to store the data in the xml file under the path "data/package name/pai_prefs.
Related connections: Data Storage in Android (1) -- SharedPreferences Data Storage
2. File Storage Data 
It can be divided into internal storage and external storage. Internal Storage is the memory space allocated by applications using Android. data is stored in the corresponding file in the "/data/package name/files" path. External Storage Uses the mobile phone sdcard memory (this sdcard is not the SD card that we often say can be removed and replaced, which is called an expansion card ), to use this part of memory, you must declare the corresponding permissions.
Related connection: Data Storage in Android (2)-file storage data
3. SQLite Database Data Storage 
The database is used for storage, which generally results in a large amount of data.
Related connection: Data Storage in Android-SQLite Database Data Storage
4. Use ContentProvider to store data 
This is quite familiar. ContentProvider is also one of the four main components of Android. ContentProvider is generally a data storage method provided by a third party. It provides contacts, photos, and music to contacts in the address book on our mobile phone ......
Related connection: Data Storage in Android-ContentProvider Data Storage
5. Network Storage Data 
This is to upload data to the network for storage.

The following describes how to use the SQLite database to store data.

SQLite Database Data Storage

  SQLite is a lightweight relational database.Since it is a relational database, it is actually similar to mysql and SQL server.
  The biggest difference between SQLite and other databases is the support for data types.When creating a TABLE, you can specify the Data Type of a column in the create table statement, but you can put any data type into any column. When a value is inserted into the database, SQLite checks its type. If this type does not match the associated column, SQLite will try to convert the value to the column type. If the conversion fails, the value is stored as its own type. For example, you can put a String in the INTEGER column. SQLite calls this "weak type" (manifest typing .).
To operate the database SQLite, we need to use the SQLiteOpenHelper class for operations. Database Operations are "add, delete, modify, and query". Before learning about database operations, we must first learn how to create a database ......

Create a database

Database Operations use SQLiteOpenHelper. SQLiteOpenHelper is an abstract class. When using SQLiteOpenHelper, we must first create a MySQLiteOpenHelper to inherit the SQLiteOpenHelper class.
SQLiteOpenHelper has two very important methods: The getReadableDatabase () method returns a read-only database; the getWriteableDatabase () method returns a read-write database object. Here we use the getWriteableDatabase () method to obtain the Database object.

Create a MySQLiteOpenHelper that inherits the SQLiteOpenHelper class:

1 public class MySQLiteOpenHelper extends SQLiteOpenHelper {2 3 // constructor, input four parameter Context objects, database name, Operation database Cursor object, version number version. 4 public MySQLiteOpenHelper (Context context, String name, SQLiteDatabase. cursorFactory factory, int version) {5 super (context, name, factory, version); 6} 7 // custom constructor 8 public MySQLiteOpenHelper (Context context, String name) {9 this (context, name, null, 1); // pass in the Context and Database name, call the above constructor 10} 11 12 @ Override13 public void onCreate (SQLiteDatabase sqLiteDatabase) {14 // when creating a database, create a data table table15 String sq L = "create table if not exists user (id integer primary key autoincrement, name varchar (20), passwords varchar (20)"; 16 sqLiteDatabase.exe cSQL (SQL ); 17 18} 19 @ Override20 public void onUpgrade (SQLiteDatabase sqLiteDatabase, int I, int i1) {21 // used to upgrade the database, you only need to input a number that is larger than the previous version when creating this class object. 22} 23}

 

Create a database:

1 // create a database 2 MySQLiteOpenHelper mySQLiteOpenHelper = new MySQLiteOpenHelper (getApplicationContext (), "create_db"); // The Database Name Is create_db. 3 SQLiteDatabase db = mySQLiteOpenHelper. getWritableDatabase ();

 

Add

Use the insert (String table, String nullColumnHack, ContentValues values) method of SQLiteDatabase to insert data. This method contains three parameters:
Let's first list an insert statement in SQLite:Insert into user (name, passwords)] VALUES ("Zhang San", "123456 "); 
String table:The name of the data table for the operation.
String nullColumnHack:This parameter is used to fill in null values for data that can be added to a data table without specifying the data to be added. Generally, this parameter is null.
ContentValues values:It is used to transmit data. Generally, we encapsulate data through the putXXX () method of the ContentValues class object, and then add the data to the database.
ContentValues class, similar to Map in java, stores data in key-value pairs.

1 ContentValues value = new ContentValues (); 2 value. put ("name", "Zhang San"); // Add "Zhang San" to the field named name in the data table ". 3 value. put ("passwords", "123456"); // Add "123456" to the field named passwords in the data table ". 4 // the db database object has been created before and is directly used here. 5 db. insert ("user", null, value); // insert data in the user data table of the database: data with the field name "Zhang San" and the field name passwords "123456.

 

Delete

Use the delete (String table, String whereClause, String [] whereArgs) method of SQLiteDatabase to delete data. This method contains three parameters:
Let's first list A Delete statement in SQLite:Delete from user WHERE name = "James".
String table:The name of the data table for the operation.
String whereClause:Conditions for row deletion. It is equivalent to "where name =?" In the SQLite statement? "Content.
String [] whereArgs:The condition that corresponds to the previous parameter to the condition that the row is deleted. It is equivalent to "Zhang San" in "where name =" Zhang San ".
NOTE: If both String whereClause and String [] whereArgs are null, all rows are deleted.

// The db database object has been created before. It is used directly here. Db. delete ("user", "name =? ", New String [] {" James "});

 

Change

Use the update (String table, ContentValues values, String whereClause, String [] whereArgs) method of SQLiteDatabase to delete data. This method contains four parameters:
Let's first list a modified statement in SQLite:UPDATE user SET name = "", passwords = "123" WHERE name = "James".
String table:The name of the data table for the operation.
ContentValues values:It is used to transmit data. Generally, we encapsulate data through the putXXX () method of the ContentValues class object, and then add the data to the database.
String whereClause:Restrict the conditions for modifying rows. It is equivalent to "where name =?" In the SQLite statement? "Content.
String [] whereArgs:The condition that corresponds to the previous parameter to the condition that the row is deleted. It is equivalent to "Zhang San" in "where name =" Zhang San ".

1 // the db database object has been created before and is directly used here. 2 ContentValues values = new ContentValues (); 3 values. put ("passwords", "abcd"); 4 db. update ("user", values, "name =? ", New String [] {" James "});

 

Query

SQLiteDatabase provides multiple methods for "query" operations.
Let's first list a modified statement in SQLite:SELECT passwords="123" FROM user.
(1) use SQL statements for queries. SQLiteDatabase provides the following methods:

  • RawQuery (String SQL, String [] selectionArgs ):This method returns the Cursor class object used to operate the query results.
1 String SQL = "select * from user"; 2 Cursor cursor = db. rawQuery (SQL, null); 3 cursor. moveToFirst (); // transfer to the first row of the Result 4 while (! Cursor. isAfterLast () {5 String name = cursor. getString (cursor. getColumnIndex ("name"); 6 String passwords = cursor. getString (cursor. getColumnIndex ("passwords"); 7 Log. d ("data", "name =" + name + "password =" + passwords); 8 cursor. moveToNext (); 9}

 

(2) Use SQLiteDatabase's internal method to query:

  • Query (String table, String [] columns, String selection, String [] selectionArgs, String groupBy, String having, String orderBy, String limit ):This method has N multiple parameters ...... String table is the name of the data table for the operation; String selection is the field option for filtering; String [] selectionArgs is the value corresponding to the field option; String groupBy is the basis for grouping the filtering result; string having is used to set conditions on the group created by the groupBy clause; String orderBy is the result sorting method, and String limit is the display limit of the filter results, for example, "2, "3" indicates that three results are displayed starting from the first one.
1 Cursor cursor = db. query ("user", null, "id desc", "2, 3"); // limit statement offset, num2 cursor. moveToFirst (); // transfer to the first row of the result 3 while (! Cursor. isAfterLast () {4 String name = cursor. getString (cursor. getColumnIndex ("name"); 5 String passwords = cursor. getString (cursor. getColumnIndex ("passwords"); 6 Log. d ("data", "name =" + name + "password =" + passwords); 7 cursor. moveToNext (); 8}

 

In this way, database operations and storage are almost the same, and database operations are nothing more than these four types ......

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.