The data storage android SQLite

Using the embedded SQLite relational database for storing data

 

In addition to using a file or data storage SharedPreferences, SQLite can choose to use the database to store data.

On the Android platform, it integrates an embedded relational database -SQLite,

1, SQLite3 support NULL, INTEGER, REAL (floating point numbers), TEXT (text string) and BLOB (binary object) data type, although it supports the type, although only five, but also to accept the fact sqlite3 varchar (n) , char (n), decimal ( p, s) and other types of data, but when the save operation or will turn to the corresponding five data types.

2, SQLite biggest feature is that you can store any type of data to any field, regardless of what type of data this column stated yes. For example: Integer field can be stored in a string, or Boolean stored in a floating-point number field, or the date stored in the character type field value.

3, but with one exception: is defined as INTEGER PRIMARY KEY field can store 64-bit integer, when saving data to an integer other than this field, it will generate an error.

4. In addition, SQLite when parsing the CREATE TABLE statement ignores the type of information the CREATE TABLE statement with the data type information in the back field names, as in the following statement ignores the name field:

CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))

 

SQLite can resolve most of the standard SQL statements, such as:

Query: select * from table where conditions clause group by grouping words having ... order by ordering clause

如:select * from person

        select * from person order by id desc

        select name from person group by name having count(*)>1

SQL mysql tab and similar, the following SQL statement to obtain five records, skip ahead three records

select * from Account limit 5 offset 3 或者 select * from Account limit 3,5

Insert statement: insert into table (field list) values ​​(list of values). Such as: insert into person (name, age) values ​​( 'pass chi', 3)

Update statement: update table set field name = value where the condition clause. Such as: update person set name = 'Chuanzhi' where id = 10

Delete statement: delete from table where conditions clause. Such as: delete from person where id = 10

 

SQLiteDatabase operation using SQLite database
Android provides SQLiteDatabase called class that encapsulates some of the operations of the database API.
You can call the static method SQLiteDatabase:
public static SQLiteDatabase openDatabase(String path,SQLiteDatabase.CursorFactory factory,int flags)
 flags parameter may be OPEN_READWRITE, OPEN_READONLY, CREATE_IF_NECESSARY, NO_LOCALIZED_COLLATORS a four or more (the combination of a plurality of modes | isolation).
public static SQLiteDatabase openOrCreateDatabase(File file,SQLiteDatabase.CursorFactory factory)
public static SQLiteDatabase openOrCreateDatabase(String path,SQLiteDatabase.CursorFactory factory)
Open the file system is located in the absolute path path of the database.
You can also call through the Context object
public abstract SQLiteDatabase openOrCreateDatabase (String name, int mode, SQLiteDatabase.CursorFactory factory) to create or open a database called the name of the database directly in a private directory,
Note: mode only is MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE.
Context also:
public abstract String [] databaseList (); // return all proprietary database directory database name
public abstract boolean deleteDatabase (String name); // delete the database named name in the private directory database file.
In addition to creating SQLite database in the file system, android supports SQLite memory database. In the case of some of the need to create a temporary database, and the operating rate is relatively high demand, SQLite database on the role of memory, static method of SQLiteDatabase:
public static SQLiteDatabase create(SQLiteDatabase.CursorFactory factory)
To create, creation fails returns null.
Finally, remember, no matter how open the database, SQLite objects that are obtained when no longer in use, should call close () to close the open database, otherwise IllegalStateException is thrown.
Use SQLiteDatabase objects can be added to complete the data (Create), query (Retrieve), update (Update) and delete (Delete) operations (these operations are referred to as CRUD). SQLiteDatabase learning, we should focus on mastering execSQL () and rawQuery () method. execSQL () method can perform insert, delete, update and the like have CREATE TABLE SQL statement to change behavior; rawQuery () method can execute select statement.
Examples execSQL using () method:
SQLiteDatabase db = ....;
db.execSQL("insert into person(name, age) values('传智播客', 4)");
db.close();
Implementation of the above SQL statement will be added to the person table into a record, in practice, the statement "Chi Chuan podcast" values ​​of these parameters should be provided by the user input interface, if the user input as it is set to fight to the top of the insert statement, when the user input contains a single quotation mark, the group will spell out the SQL statement for syntax errors. To solve this problem needs to be escaped single quotes, which is converted into two single quotes single quotes. Sometimes users will often enter as "&" SQL these special symbols, in order to ensure a good group to fight the SQL statement syntax is correct, it is necessary for these special symbols SQL SQL statements are escape, obviously, for each SQL statement doing so processing is more cumbersome. SQLiteDatabase class provides execSQL after a heavy load (String sql, Object [] bindArgs) method, using this method can solve the problems mentioned above, because this method supports the use of parameter placeholders (?). Use examples:
SQLiteDatabase db = ....;
db.execSQL("insert into person(name, age) values(?,?)", new Object[]{"传智播客", 4}); 
db.close();
execSQL (String sql, Object [] bindArgs) The first argument of the SQL statement, the value of the second parameter placeholder parameter SQL statement, and the parameter value to the position corresponding to the order of the placeholder array .
SQLiteDatabase the rawQuery () for performing the select statement, using the following example: SQLiteDatabase db = ....;
Cursor cursor = db.rawQuery(“select * from person”, null);
while (cursor.moveToNext()) {
int personid = cursor.getInt (0); // get the value of the first column, the first column of the index starts from 0
String name = cursor.getString (1); // get the value of the second column
int age = cursor.getInt (2); // get the value of the third column
}
cursor.close();
db.close(); 
The first parameter rawQuery () method to select statement; second parameter value select statement placeholder parameter, if no placeholders select statement, this parameter can be set to null. With placeholder parameter select statement using the following examples:
Cursor cursor = db.rawQuery("select * from person where name like ? and age=?", new String[]{"%传智%", "4"});
 
Cursor is the cursor result set, the result set for random access, if you are familiar with jdbc, and in fact ResultSet Cursor role in JDBC is very similar. Use MoveToNext () method may move the cursor from the current line to the next line, if the line has moved through the final result set, it returns a value of false, otherwise true. Further there are common MoveToPrevious Cursor () method (for the current line from the cursor moves to the line, if a has moved through the first row of the result set, the return value is false, otherwise it is true), moveToFirst () method ( move the cursor to the first row of the result set, if the result set is empty, the return value is false, otherwise it is true) and moveToLast () method (to move the cursor to the last row of the result set if the result is set empty, the return value is false, otherwise true).
In addition to execSQL front to introduce () and rawQuery () method, SQLiteDatabase also specializes corresponding to add, delete, update, query methods of operation: insert (), delete (), update () and query (). For programmers familiar with SQL syntax, use these methods are actually for those who do not understand SQL syntax used execSQL () and rawQuery () method executes SQL statements that can be done to add data, delete, update , query operation.
Insert () method is used to add data, each field using ContentValues ​​for storage. ContentValues ​​similar to MAP, with respect to the MAP, which provides access to the data corresponding to the put (String key, Xxx value) and getAsXxx (String key) method, key field name, value for the field value, Xxx refers to a variety of commonly used data types, such as: String, Integer like.
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "传智播客");
values.put("age", 4);
long rowid = db.insert ( "person", null, values); // returns independent line number added a new record, the primary key id
Regardless of whether the third parameter contains the data, execution Insert () method is bound to add a record, if the third parameter is empty, a record is added other than the primary key field value other than Null. Internal () method Insert actually completed by constructing the insert statement to add data, the second argument Insert () method specifies the name of the field null value, we believe that this parameter will wonder, why is the role of this parameter of? Is such that: if the values of the third parameter is the number of elements is Null or 0, Insert () method is bound to add an additional field to Null value recording in addition to the primary key, in order to meet this insert statement syntax, insert statement It must be given a field name, such as: insert into person (name) values (NULL), if not the given field name, insert statements became so: insert into person () values ( ), which obviously does not meet the standard SQL grammar. For field names, it is recommended to use a field other than the primary key, if used INTEGER primary key field, performs a similar insert into person (personid) values ( NULL) insert statement, the primary key field value will not be NULL. If the third parameter is not Null values and the number of elements is greater than 0, the second parameter may be set to null.
delete () method of use:
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.delete("person", "personid<?", new String[]{"2"});
db.close();
The above code is used to delete the record is less than 2 personid from the person table.
 
update () method is used:
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put ( "name", "Chuan Chi podcast"); // key is the field name, value is the value
db.update("person", values, "personid=?", new String[]{"1"}); 
db.close();
The above code is used to change the value to equal personid person table name field 1 records the "Biography Chi podcast."
query () method to select statement is actually split into several components and method as input parameters:
SQLiteDatabase db = databaseHelper.getWritableDatabase();
Cursor cursor = db.query("person", new String[]{"personid,name,age"}, "name like ?", new String[]{"%溧阳%"}, null, null, "personid desc", "1,2");
while (cursor.moveToNext()) {
         int personid = cursor.getInt (0); // get the value of the first column, the first column of the index starts from 0
        String name = cursor.getString (1); // get the value of the second column
        int age = cursor.getInt (2); // get the value of the third column
}
cursor.close();
db.close(); 
The above code is used to look up the name field from the person table containing records "pass wisdom", by matching records personid descending order, the results sorted skip the first record, acquiring only two records.
query (table, columns, selection, selectionArgs, groupBy, having, orderBy, limit) the method parameters meanings:
table: table name. The portion corresponding to the back of the select statement from keywords. If it is a joint multi-table queries, you can use a comma to separate two table names.
columns: To check out the column names. The portion corresponding to the back of the select statement select keywords.
selection: query clause, the portion corresponding to the back of the select statement where keywords in clause allows the use of placeholder "?"
selectionArgs: the value corresponding to the selection statement placeholder, the values ​​in the array position and the placeholders in the statement must be the same, otherwise there will be abnormal.
groupBy: the equivalent part of the group behind the select statement by keyword
having: a portion corresponding to the back of the select statement to having keywords
orderBy: corresponding to the rear portion of the key by the select statement order, such as: personid desc, age asc;
limit: Specifies the number of records and the offset acquired, the portion corresponding to the back limit keyword select statement.
 
SQLiteOpenHelper use the database version management
If the application to use the SQLite database when the user first use the software, you need to create applications that use the database table structure and add some initialization record, the other when software upgrades, data table structures also need to be updated. In the Android system, provides us with a class called SQLiteOpenHelper, the class is used to manage the database version, the class is an abstract class must inherit it to use. In order to achieve the database version management, SQLiteOpenHelper class has two important methods are onCreate (SQLiteDatabase db) and onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion). You can also implement public abstract void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) method, which was first performed after each successful open database, the default implementation of this method in the case is empty.
 
When the call SQLiteOpenHelper getWritableDatabase () or getReadableDatabase () method to get SQLiteDatabase for example of the operation time database, if the database does not exist, Android system will automatically generate a database, then call onCreate () method, onCreate () method to generate the initial It will be called when the database, you can generate database table structure in onCreate () method and add in some applications to use initialization data. onUpgrade () method is called when the version of the database changes, the version of the database is controlled by the programmer, it assumes that the database version is now 1, due to the need of business, modified the structure of the database table, this time you need to upgrade software, software upgrades want to update the phone's user database table structure, in order to achieve this purpose, the original version of the database is set to 2 (3 students asked to okay? of course you can, if you like, is set to 100 too), and to realize structure in which the update table onUpgrade () method. When more software version upgrade number, in this case onUpgrade () method which can be determined in accordance with the original target number and version number, and then make the appropriate table structure and data updates.
 
getWritableDatabase () and getReadableDatabase () method can be used to obtain a SQLiteDatabase example operation database. But getWritableDatabase () method to open the database to read and write, once the database disk space is full, the database can only be read but not write, if using getWritableDatabase () method will be wrong. getReadableDatabase () method to open the database to read and write, if a database disk space is full, it will fail to open, when open failure will continue to try to open read-only database. However, if this method is called again, then, the problem has been resolved, read-only SQLiteDatabase object will be closed, and return to SQLiteDatabase database object that you can read and write.
public class DatabaseHelper extends SQLiteOpenHelper {
    // parameters without instantiating the class, can not be used as a parent class constructor must be declared as static
         private static final String name = "itcast"; // database name
         private static final int version = 1; // Database Version
         public DatabaseHelper(Context context) {
// The third parameter specifies the CursorFactory get a cursor instance when performing a query factory class, set the default to null, use the system on behalf of the factory class
                super(context, name, null, version);
         }
        @Override public void onCreate(SQLiteDatabase db) {
              db.execSQL("CREATE TABLE IF NOT EXISTS person (personid integer primary key autoincrement, name varchar(20), age INTEGER)");   
         }
        @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
               db.execSQL("DROP TABLE IF EXISTS person");
               onCreate(db);
         }
}
Above onUpgrade () method will put the database on the user's mobile phone to delete tables in the database version changes each time, and then re-created. Generally in the actual project is unable to do so, the correct approach is in updating the database table structure, but also consider the user stored in the database data is not lost.
 
Examples of use SQLiteOpenHelper acquisition database operation SQLiteDatabase
public class DatabaseHelper extends SQLiteOpenHelper {
         private static final String name = "itcast"; // database name
         private static final int version = 1; // Database Version
         ......slightly
}
public class HelloActivity extends Activity {
    @Override public void onCreate(Bundle savedInstanceState) {
        ......
        Button button =(Button) this.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
DatabaseHelper databaseHelper = new DatabaseHelper(HelloActivity.this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.execSQL("insert into person(name, age) values(?,?)", new Object[]{"传智播客", 4});
db.close();  
}});        
    }
}
After the first call getWritableDatabase () or getReadableDatabase () method, SQLiteOpenHelper will cache the current SQLiteDatabase example, under normal circumstances SQLiteDatabase instance will remain open database, so when you no longer need SQLiteDatabase instance, call promptly close () method to release resources. Once SQLiteDatabase cached instance is called multiple times getWritableDatabase () or getReadableDatabase () obtained by the method are the same instance.
 
Use SQLite database transaction operations
SQLiteDatabase use of beginTransaction () method can open a transaction, program execution to endTransaction () will check mark whether the transaction is successful when a method, if the transaction is committed to the success, or roll back the transaction. When the application needs to be submitted before the transaction must be performed to endTransaction program () method uses setTransactionSuccessful () method to set a sign for the success of the transaction, if you do not call setTransactionSuccessful () method, the default will roll back the transaction. Examples of use follows: SQLiteDatabase db = ....;
db.beginTransaction (); // Begin a transaction
try {
    db.execSQL("insert into person(name, age) values(?,?)", new Object[]{"传智播客", 4});
    db.execSQL("update person set name=? where personid=?", new Object[]{"传智", 1});
    db.setTransactionSuccessful (); // This method is called when the current transaction will be submitted to the Executive endTransaction (), if you do not call this method will roll back the transaction
} finally {
    db.endTransaction (); // is determined by the sign of the transaction is to commit the transaction, or roll back the transaction
db.close(); 
The above two SQL statements executed in the same transaction.
SQLite sample program

   1. create an Android project

       Project name: db

       BuildTarget:Android2.2

       Application name: Application Database

       Package name: com.jbridge.db

       Create Activity: DBActivity

       Min SDK Version:8、

 2. Person entity

 

package com.jbridge.domain;

import android.R.string;

public class Person {
	private Integer id;
	private String name;
	private Short age;

	public Person(String name, Short age) {
		this.name = name;
		this.age = age;
	}

	public Person(Integer id, String name, Short age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Short getAge() {
		return age;
	}

	public void setAge(Short age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

}

 

  3. write DataBaseOpenHelper class

      DataBaseOpenHelper SQLiteOpenHelper inherited from class. We need to create a data table, you must override onCreate (rewrite onUpgrade method when updating) method, create a data table in this method.

package com.jbridge.service;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseOpenHelper extends SQLiteOpenHelper {
	// 类没有实例化,是不能用作父类构造器的参数,必须声明为静态
	private static String dbname = "zyj";
	private static int version = 1;

	public DataBaseOpenHelper(Context context) {
		// 第一个参数是应用的上下文
		// 第二个参数是应用的数据库名字
		// 第三个参数CursorFactory指定在执行查询时获得一个游标实例的工厂类,设置为null,代表使用系统默认的工厂类
		// 第四个参数是数据库版本,必须是大于0的int(即非负数)
		super(context, dbname, null, version);
		// TODO Auto-generated constructor stub
	}

	public DataBaseOpenHelper(Context context, String name,
			CursorFactory factory, int version) {
		super(context, name, factory, version);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE IF NOT EXISTS person (personid integer primary key autoincrement, name varchar(20), age INTEGER)");
	}

	// onUpgrade()方法在数据库版本每次发生变化时都会把用户手机上的数据库表删除,然后再重新创建。
	// 一般在实际项目中是不能这样做的,正确的做法是在更新数据库表结构时,还要考虑用户存放于数据库中的数据不会丢失,从版本几更新到版本几。
	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
		db.execSQL("DROP TABLE IF EXISTS person");
		onCreate(db);
	}

}

 4. writing class PersonService

      PersonService principal implement business logic and operation of the database

 

package com.jbridge.service;

import java.util.ArrayList;
import java.util.Currency;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.jbridge.domain.Person;

public class PersonService {

	private DataBaseOpenHelper dbOpenHelper;

	// private Context context;

	public PersonService(Context context) {
		// this.context = context;
		dbOpenHelper = new DataBaseOpenHelper(context);
	}

	public void save(Person person) {
		SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
		database.beginTransaction();
		database.execSQL("insert into person(name,age)values(?,?)",
				new Object[] { person.getName(), person.getAge() });
		// database.close();可以不关闭数据库,他里面会缓存一个数据库对象,如果以后还要用就直接用这个缓存的数据库对象。但通过
		// context.openOrCreateDatabase(arg0, arg1, arg2)打开的数据库必须得关闭
		database.setTransactionSuccessful();
		database.endTransaction();

	}

	public void update(Person person) {
		SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
		database.execSQL(
				"update person set name=?,age=? where personid=?",
				new Object[] { person.getName(), person.getAge(),
						person.getId() });
	}

	public Person find(Integer id) {
		SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
		Cursor cursor = database.rawQuery(
				"select * from person where personid=?",
				new String[] { String.valueOf(id) });
		if (cursor.moveToNext()) {
			return new Person(cursor.getInt(0), cursor.getString(1),
					cursor.getShort(2));
		}
		return null;
	}

	public void delete(Integer... ids) {
		if (ids.length > 0) {
			StringBuffer sb = new StringBuffer();
			for (Integer id : ids) {
				sb.append('?').append(',');
			}
			sb.deleteCharAt(sb.length() - 1);
			SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
			database.execSQL(
					"delete from person where personid in(" + sb.toString()
							+ ")", ids);
		}
	}

	public List<Person> getScrollData(int startResult, int maxResult) {
		List<Person> persons = new ArrayList<Person>();
		SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
		Cursor cursor = database.rawQuery(
				"select * from person limit ?,?",
				new String[] { String.valueOf(startResult),
						String.valueOf(maxResult) });
		while (cursor.moveToNext()) {
			persons.add(new Person(cursor.getInt(0), cursor.getString(1),
					cursor.getShort(2)));
		}
		return persons;
	}

	// 获取分页数据,提供给SimpleCursorAdapter使用。
	public Cursor getRawScrollData(int startResult, int maxResult) {
		List<Person> persons = new ArrayList<Person>();
		SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
		return database.rawQuery(
				"select personid as _id ,name,age from person limit ?,?",
				new String[] { String.valueOf(startResult),
						String.valueOf(maxResult) });

	}

	public long getCount() {
		SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
		Cursor cursor = database.rawQuery("select count(*) from person", null);
		if (cursor.moveToNext()) {
			return cursor.getLong(0);
		}
		return 0;
	}

}

  The following is an  INSERT (), Delete (), Update () and the query () method to achieve traffic class

package com.jbridge.service;

import java.util.ArrayList;
import java.util.Currency;
import java.util.List;

import android.R.string;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.jbridge.domain.Person;

public class OtherPersonService {

	private DataBaseOpenHelper dbOpenHelper;

	// private Context context;

	public OtherPersonService(Context context) {
		// this.context = context;
		dbOpenHelper = new DataBaseOpenHelper(context);
	}

	public void save(Person person) {
		SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
		ContentValues contentValues = new ContentValues();
		contentValues.put("name", person.getName());
		contentValues.put("age", person.getAge());
		database.insert("person", null, contentValues);
	}

	public void update(Person person) {
		SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
		ContentValues contentValues = new ContentValues();
		contentValues.put("name", person.getName());
		contentValues.put("age", person.getAge());
		database.update("person", null, "personid=?",
				new String[] { String.valueOf(person.getId()) });
	}

	public Person find(Integer id) {
		SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
		Cursor cursor = database.query("person", new String[] { "personid",
				"name", "age" }, "personid=?",
				new String[] { String.valueOf(id) }, null, null, null);
		if (cursor.moveToNext()) {
			return new Person(cursor.getInt(0), cursor.getString(1),
					cursor.getShort(2));
		}
		return null;
	}

	public void delete(Integer... ids) {
		if (ids.length > 0) {
			StringBuffer sb = new StringBuffer();
			String[] strIds = new String[ids.length];
			// for (Integer id : ids) {
			// sb.append('?').append(',');
			// }
			for (int i = 0; i < strIds.length; i++) {
				sb.append('?').append(',');
				strIds[i] = String.valueOf(ids[i]);
			}
			sb.deleteCharAt(sb.length() - 1);
			SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
			database.delete("person", "personid in(" + sb.toString() + ")",
					strIds);
		}
	}

	public List<Person> getScrollData(int startResult, int maxResult) {
		List<Person> persons = new ArrayList<Person>();
		SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
		Cursor cursor = database.query("person", new String[] { "personid",
				"name", "age" }, null, null, null, null, "personid desc",
				startResult + "," + maxResult);
		while (cursor.moveToNext()) {
			persons.add(new Person(cursor.getInt(0), cursor.getString(1),
					cursor.getShort(2)));
		}
		return persons;
	}

	public long getCount() {
		SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
		Cursor cursor = database.query("person", new String[] { "count(*)" },
				null, null, null, null, null);
		if (cursor.moveToNext()) {
			return cursor.getLong(0);
		}
		return 0;
	}

}

   5. write test classes

       PersonService for the preparation of a test class, test PersonService class each method is correct

package com.jbridge.db;

import java.util.List;

import com.jbridge.domain.Person;
import com.jbridge.service.OtherPersonService;
import com.jbridge.service.PersonService;

import android.test.AndroidTestCase;
import android.util.Log;

public class PersonServiceTest extends AndroidTestCase {
	private static String TAG = "PersonServiceTest";

	// OtherPersonService personService = new
	// OtherPersonService(this.getContext());
	// //不可以这么写,因为Android把context环境变量是在PersonServiceTest实例化后给他的

	public void testSave() throws Exception {
		PersonService personService = new PersonService(this.getContext());
		// personService.save(new Person("老猪", (short) 11));
		for (int i = 0; i < 10; i++) {
			personService.save(new Person("你" + i, (short) (i + 10)));
		}

	}

	public void testFind() throws Exception {
		PersonService personService = new PersonService(this.getContext());
		Person person = personService.find(1);
		Log.i(TAG, person.toString());
	}

	public void testUpdate() throws Exception {
		PersonService personService = new PersonService(this.getContext());
		Person person = personService.find(1);
		person.setName("lv");
		personService.update(person);
	}

	public void testDelete() throws Exception {
		PersonService personService = new PersonService(this.getContext());
		personService.delete(1, 2, 3);
	}

	public void testGetCount() throws Exception {
		PersonService personService = new PersonService(this.getContext());
		Log.i(TAG, String.valueOf(personService.getCount()));
	}

	public void testGetScrollData() throws Exception {
		PersonService personService = new PersonService(this.getContext());
		List<Person> persons = personService.getScrollData(0, 3);
		for (Person person : persons) {
			Log.i(TAG, person.toString());
		}
	}
}

 

Reproduced in: https: //www.cnblogs.com/sunfb/p/3956058.html

Guess you like

Origin blog.csdn.net/weixin_33714884/article/details/94698827