Android entry notes-data storage-SQLite, unit test

Source: Internet
Author: User

Android entry notes-data storage-SQLite, unit test

Why do we need to add three lightweight databases (SQLite) today? Because it is really light. Sqlite is a lightweight database specially prepared by unembedded devices. Although it is small, it has many functions. The biggest difference between it and other databases: MySql, SqlServer, Oracle and other databases I think is that Sqlite can only run on terminals and cannot be used on servers, this also reflects its original intention to work for embedded devices.

Let's take a look at today's content:

SQLiteAndroid unit test

Today, we will not only introduce sqlite, but also briefly introduce how to use android unit testing. If you don't know what unit testing is, go to google!


To use the sqlite database in android, you generally need to use a helper class: SQLiteOpenHelper, which has two methods: onCreate (), and onUpgrade ().

OnCreate () is called when the database is created for the first time. OnUpgrade () is called when the database version is updated.

What does that mean? Let's look at the Code:

package db;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteOpenHelper;import android.transition.Transition;import android.util.Log;public class DBOpenHelper extends SQLiteOpenHelper {private static final String TAG = "DBOpenHelper";private Context mContext;private String mDBname;private String mTableName = "students";private SQLiteDatabase mDatabase;private int mVersion;private String CREATE_TABLE = "create table if not exists " + mTableName+ " (_id integer primary key, name text)";public DBOpenHelper(Context context, String dbname, CursorFactory factory,int version) {super(context, dbname, factory, version);this.mContext = context;this.mDBname = dbname;this.mVersion = version;}@Overridepublic void onCreate(SQLiteDatabase db) {Log.e(TAG, "onCreate");db.execSQL(CREATE_TABLE);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {Log.e(TAG, "onUpgrade");}public long insert(String data) {if (mDatabase == null) {mDatabase = getWritableDatabase();}ContentValues values = new ContentValues();values.put("name", data);return mDatabase.insert(mTableName, "_id", values);}public int delete(int id) {if (mDatabase == null) {mDatabase = getWritableDatabase();}return mDatabase.delete(mTableName, "_id" + "=" + id, null);}public int update(int id, String data) {if (mDatabase == null) {mDatabase = getWritableDatabase();}ContentValues values = new ContentValues();values.put("name", data);return mDatabase.update(mTableName, values, "_id" + "=" + id, null);}public Cursor getItemAt(int id) {if (mDatabase == null) {mDatabase = getWritableDatabase();}Cursor cursor = mDatabase.query(mTableName, new String[] { "_id","name" }, "_id" + "=" + id, null, null, null, null, null);if (cursor != null) {cursor.moveToFirst();}return cursor;}public Cursor getAll() {if (mDatabase == null) {mDatabase = getWritableDatabase();}Cursor cursor = mDatabase.query(mTableName, new String[] { "_id","name" }, null, null, null, null, null);return cursor;}}
When using SqliteOpenHelper, these three methods are required:

public DBOpenHelper(Context context, String dbname, CursorFactory factory,int version) {super(context, dbname, factory, version);this.mContext = context;this.mDBname = dbname;this.mVersion = version;}@Overridepublic void onCreate(SQLiteDatabase db) {Log.e(TAG, "onCreate");db.execSQL(CREATE_TABLE);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {Log.e(TAG, "onUpgrade");}
The constructor completes the initialization of Context, database name, and database version. The value of CursorFactory is null.

In onCreate (), we call db.exe cSQl (CREATE_TABLE); initialize a table named "students", and the DBOpenHelper class will work for this table.

As for onUpdrade (), when calling the constructor, if the version value is greater than the previous value, it will be triggered. Then, onUpgrade () is mainly used to modify the table data columns, back up data and so on.

Then let's see how the addition, deletion, modification, and query of the database are completed:


Add:

Using the ContentValues provided by android, you can easily initialize the object to be added. It is equivalent to a key-value pair. If there are multiple objects, you can use the put Method to add them one by one, note that the key must correspond to the columns in the database.

Here, mDatabase is a SqliteDatabase object that is used to operate databases. It can be obtained through SqliteOpenHelper. getWritableDatabase (), and then data can be inserted by calling the insert () method. Note that when using sqlite, the table must have a field named "_ id" and the primary key is auto-incrementing. This is the value of the second parameter of insert.

Equivalent to executing an SQL statement:

Insert into students (_ id, name) values (id, name );

public long insert(String data) {if (mDatabase == null) {mDatabase = getWritableDatabase();}ContentValues values = new ContentValues();values.put("name", data);return mDatabase.insert(mTableName, "_id", values);}


Delete:

The second parameter is a string, which is equivalent to: "where _ id = id", but the delete method is concatenated by itself.

Equivalent to executing an SQL statement:

Delete from students where _ id = id;

public int delete(int id) {if (mDatabase == null) {mDatabase = getWritableDatabase();}return mDatabase.delete(mTableName, "_id" + "=" + id, null);}


Change:

The update method must provide conditions and modified values, corresponding to the values and "_ id" = id parameters.

Equivalent to executing an SQL statement:

Update students where _ id = id set name = "data ";

public int update(int id, String data) {if (mDatabase == null) {mDatabase = getWritableDatabase();}ContentValues values = new ContentValues();values.put("name", data);return mDatabase.update(mTableName, values, "_id" + "=" + id, null);}

Query:

It should be noted that the cursor is used in android as the result set (ResultSet in java). If the cursor is found, it is returned before the data in the first row. Therefore, you need to call cursor once. moveToFirst () or cursor. moveToNext () to point to the first row of data.

public Cursor getItemAt(int id) {if (mDatabase == null) {mDatabase = getWritableDatabase();}Cursor cursor = mDatabase.query(mTableName, new String[] { "_id","name" }, "_id" + "=" + id, null, null, null, null, null);if (cursor != null) {cursor.moveToFirst();}return cursor;}public Cursor getAll() {if (mDatabase == null) {mDatabase = getWritableDatabase();}Cursor cursor = mDatabase.query(mTableName, new String[] { "_id","name" }, null, null, null, null, null);return cursor;}

Now, the sqlite operation is complete. Let's see how to use the DBOpenHelper class. At this time, we used the unit test of Android.

Android unit test configuration method:

1. Add registration in the AndroidMainefest. xml file.

Add between tags:

Add under the root tag: Android: name = "android. test. InstrumentationTestRunner"> (Fill in the package name of the first Activity of the program in the bold Section)

2. The test class must inherit from AndroidTestCase.

3. Each test method uses the test + method name as the test method name, and an exception must be thrown.

Let's look at the Code:

package Test;import db.DBOpenHelper;import android.database.Cursor;import android.test.AndroidTestCase;import android.util.Log;public class TestDBOpenHelper extends AndroidTestCase {private static final String TAG = "TestDBOpenHelper";public void TestInsert() throws Throwable{Log.e(TAG,"TestInsert");DBOpenHelper dbopenhelper = new DBOpenHelper(mContext, "stu.db", null, 1);dbopenhelper.insert("stu1");dbopenhelper.insert("stu2");dbopenhelper.insert("stu3");dbopenhelper.insert("stu4");dbopenhelper.insert("stu5");}public void TestDelete(){DBOpenHelper dbopenhelper = new DBOpenHelper(mContext, "stu.db", null, 1);dbopenhelper.delete(1);dbopenhelper.delete(2);}public void TestUpdate(){DBOpenHelper dbopenhelper = new DBOpenHelper(mContext, "stu.db", null, 1);dbopenhelper.update(3, "333");dbopenhelper.update(4, "444");}public void TestGetItemAtId(){Log.e(TAG,"TestGetItemAtId");DBOpenHelper dbopenhelper = new DBOpenHelper(mContext, "stu.db", null, 1);Cursor cursor = dbopenhelper.getItemAt(3);Log.e(TAG,"_id="+cursor.getInt(0));Log.e(TAG,"name="+cursor.getString(1));}public void TestGetAll(){Log.e(TAG,"TestGetAll");DBOpenHelper dbopenhelper = new DBOpenHelper(mContext, "stu.db", null, 1);Cursor cursor = dbopenhelper.getAll();while(cursor.moveToNext()){Log.e(TAG,"_id="+cursor.getInt(0));Log.e(TAG,"name="+cursor.getString(1));}}}

After writing the code, we can start the unit test to test the code we wrote:


If it is correct, green bars will be displayed. If it is abnormal, red bars will be displayed:


Unit testing has many benefits. comrades who care about code quality should learn how to use unit testing. It is generated to verify that each code block works normally.

The test code should be easy to understand:

This is to add data in the test. You only need to create a new helper object and then call the insert method. Is it easy:

Test insertion:

public void TestInsert() throws Throwable{Log.e(TAG,"TestInsert");DBOpenHelper dbopenhelper = new DBOpenHelper(mContext, "stu.db", null, 1);dbopenhelper.insert("stu1");dbopenhelper.insert("stu2");dbopenhelper.insert("stu3");dbopenhelper.insert("stu4");dbopenhelper.insert("stu5");}

Test deletion:

public void TestDelete(){DBOpenHelper dbopenhelper = new DBOpenHelper(mContext, "stu.db", null, 1);dbopenhelper.delete(1);dbopenhelper.delete(2);}

Test search:

public void TestGetAll(){Log.e(TAG,"TestGetAll");DBOpenHelper dbopenhelper = new DBOpenHelper(mContext, "stu.db", null, 1);Cursor cursor = dbopenhelper.getAll();while(cursor.moveToNext()){Log.e(TAG,"_id="+cursor.getInt(0));Log.e(TAG,"name="+cursor.getString(1));}}
As we can see, the getAll () function returns a cursor. We can traverse the objects in each cursor cyclically. You can obtain the value of a column in cursor through cursor. getXXX (index). index is the column number, starting from 0. Of course, you can also obtain the value by column name. In general, a row of Cursor is like a Map, which stores the key-value pairs of a row of data in the database.


Well, finally, let's talk about it. The above example is very nonstandard. Of course, it is just to show how to use Sqlite to access data. In actual development, the input content should be an object, which needs to be combined with JavaBean. That is to say, the data stored in the database is actually stored for the attribute value of a Class, rather than a single value. Each row in the database stores all the attributes of an object. Of course, it may also contain several tables.


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.