Quick Android development-use ORMLite to operate databases

Source: Internet
Author: User

Quick Android development-use ORMLite to operate databases

OrmLite is an open-source framework supporting database operations. It is mainly oriented to the Java language. In Android database-oriented development, it is a popular open-source framework that is easy to operate and powerful. Let's take a look at it today. It's also involved in recent projects. Let's write a blog to record it, thanks to the great god team for contributing to such a practical open-source framework,

Prerequisites-create a database and a data table

ORMlite uses Java annotations to establish a ing relationship with the database. Here we describe it with an instance. For example, we want to create a simple database test. db and create a table "person" to record a person's name, age, and address.

Create Bean class

First, establish our Bean class Person and associate it with the database through annotation.

@DatabaseTable(tableName = person)public class Person {    @DatabaseField(generatedId=true)    private int id;    @DatabaseField(columnName=name)    private String name;    @DatabaseField(columnName=age)    private int age;    @DatabaseField(columnName=address)    private String address;    /**     * @return the id     */    public int getId() {        return id;    }    /**     * @param id the id to set     */    public void setId(int id) {        this.id = id;    }    /**     * @return the name     */    public String getName() {        return name;    }    /**     * @param name the name to set     */    public void setName(String name) {        this.name = name;    }    /**     * @return the age     */    public int getAge() {        return age;    }    /**     * @param age the age to set     */    public void setAge(int age) {        this.age = age;    }    /**     * @return the address     */    public String getAddress() {        return address;    }    /**     * @param address the address to set     */    public void setAddress(String address) {        this.address = address;    }}

Here we have created a Bean class and established a connection with the database. There are two things we need to do.
1. Enter the table name in the @ DatabaseTable annotation.
2. Fill in the field name in @ DatabaseField (columnName = "") and set the field attributes.

Field attribute description

ORMLite provides comprehensive support for field attributes. Let's take a look at it for details:

CloumnName: Specifies the field name. If not specified, the variable name is used as the field name canBeNull: can it be null dataType: Specifies the field type foreign, and specifies that the object of this field is a foreign key, the foreign key value is the id of this object. If the foreign key foreignAutoCreate does not exist, whether to automatically add it to the foreign key value in the foreign table foreignColumnName foreign key field to automatically refresh which field in the foreign key table is generatedId: the specified field is an auto-increment id and cannot be an id. generatedIdSequence universal id: Specify the field as id index: index persisted: specify whether the variable is persistent. The default value is true throwIfNull. If the null value throws an exception useGetSet: set is used to specify the ormlite access variable. The get method uses the reflection mechanism to directly access the variable unique by default: the value of the unique field value uniqueIndex unique index uniqueCombo the value of the entire column is unique to create a database

Similar to database creation in Android, using OrmLite to create a database requires us to create a SqlOpenHelper to inherit OrmLiteSqliteOpenHelper. There are also two important methods in OrmLiteSqliteOpenHelper: onCreate and onUpgrade, responsible for database creation and upgrade operations

Public class MySqlOpenHelper extends OrmLiteSqliteOpenHelper {private Dao
  
   
MPersonDao; public MySqlOpenHelper (Context context) {super (context, test, null, 1); // TODO Auto-generated constructor stub} @ Override public void onCreate (SQLiteDatabase arg0, connectionSource arg1) {// TODO Auto-generated method stub try {// create a data table TableUtils. createTableIfNotExists (arg1, Person. class);} catch (java. SQL. SQLException e) {// TODO Auto-generated catch block e. printStackTrace () ;}@ Override public void onUpgrade (SQLiteDatabase arg0, ConnectionSource arg1, int arg2, int arg3) {// TODO Auto-generated method stub} public Dao
   
    
GetPersonDao () throws java. SQL. SQLException {if (mPersonDao = null) {mPersonDao = getDao (Person. class);} return mPersonDao ;}}
   
  

Dao is a very important class. These Dao objects are used for subsequent database operations. They contain two generic and the first class for DAO operations in a generic table, the second is to mark the ID of the data table.

Database Operations

After creating our own database, we can operate on the database. Next we will see how to add, delete, query, and modify the database.

Insert operation

These methods are simple to use. You only need to pass your Bean to the following methods:

Create: Insert a piece of data createIfNotExists: if it does not exist, insert createOrUpdate: If it exists, update the query operation

OrmLite provides me with a series of query operations, many methods, and many of them can be known only by method name. Here we will not introduce them one by one, this section describes how to use QueryBuilder to perform complex search.

Call personDao. queryBuilder (); obtain the QueryBuilder object under the Dao, set the query conditions of QueryBuilder, and obtain the List object through the query method of QueryBuilder,

The following describes the queries under several commonly used builders,
1. Multi-field condition query:

QueryBuilder builder = dao. queryBuilder (); builder. where (). eq (field name 1, condition 1 ). and. eq (field name 2, condition 2); builder. query ();

2. query and output in order

QueryBuilder
  
   
Builder = dao. queryBuilder (); builder. orderBy (field name, true); builder. query ();
  

The first parameter of the orderBy method indicates that the order is based on that field, and the second parameter indicates whether the order is ascending.

3. Paging Query

QueryBuilder
  
   
Builder = dao. queryBuilder (); builder. offset (10); // indicates the start position of the Query builder. limit (10); // indicates the total number of retrieved objects builder. query ();
  
Delete and change operations

Similar to query operations, ORMLite also provides a series of methods for us and also provides DeleteBuilder and UpdateBuilder for complex deletion and modification. Their usage is similar to QueryBuilder and will not be detailed.

Place the database on the SD card

The default storage path for creating a database in Android is under the/data/packagename/database directory. On the one hand, if the database is large enough to occupy the system storage space, and on the other hand, if the system ROOT permission is not obtained, the database cannot be viewed intuitively. In the end, we will introduce how to create a database under the specified SD card directory.

This is not provided in ORMLite. You can write it yourself. After reading the Android source code, you can easily find that the directory stored in the Android database is determined by the public File getDatabasePath (String name) method in the ContextWrapper class, we only need to create our own Context to overwrite this method.

Public class DatabaseContext extends ContextWrapper {private static final String ROOT_SDCARD = Environment. getExternalStorageDirectory (). getAbsolutePath (); private String dbDir; public DatabaseContext (Context base, String path) {super (base); dbDir = path ;}@ Override public File getDatabasePath (String name) {// determine whether the SD card boolean sdExist = android exists. OS. environment. MEDIA_MOUNTED. equals (android. OS. Environment. getExternalStorageState (); if (! SdExist) {// if it does not exist, Log. e (Database error, SD card does not exist); return null;} // determines whether the directory exists. if not, create the directory File dirFile = new File (dbDir); if (! DirFile. exists () dirFile. mkdirs (); // indicates whether the database File is successfully created. boolean isFileCreateSuccess = false; String dbPath = dbDir ++ name; // The database path File dbFile = new File (dbPath ); // if the database file does not exist, create the file if (! DbFile. exists () {try {isFileCreateSuccess = dbFile. createNewFile (); // Create File} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} else isFileCreateSuccess = true; // returns the database file object if (isFileCreateSuccess) return dbFile; else return null;} @ Override public SQLiteDatabase openOrCreateDatabase (String name, int mode, SQLiteDatabase. cursorFactory factory) {SQLiteDatabase Result = SQLiteDatabase. openOrCreateDatabase (getDatabasePath (name), null); return result;}/*** Android 4.0 calls this method to obtain the database. **/@ Override public SQLiteDatabase openOrCreateDatabase (String name, int mode, CursorFactory factory, DatabaseErrorHandler errorHandler) {SQLiteDatabase result = SQLiteDatabase. openOrCreateDatabase (getDatabasePath (name), null); return result ;}}

Then, when creating SQLOpenHelper, we only need to input our own DatabaseContext, as shown in figure

SdCardDBHelper dbHelper = new SdCardDBHelper(new DatabaseContext(                MainActivity.this, path), person.db);
 

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.