In Android, when the amount of data is relatively large or for security reasons, the built-in Android database – SQLite will be used: However, sqLite should be used to consider the following points:

1. Strictly control the opening and closing of database resources (DB, CURSOR); 2. When traversing the data, obtain a cursor, convert it to list, and then use 3. Transaction rollback can greatly optimize the efficiency of the database;Copy the code

In Android development we will encounter some databases, the internal framework to do a package to use more convenient: such as ormLite greenDao

In comparison, Greendao should be the fastest and most efficient database framework (greendao website is introduced),ok direct code details greemDAO. To get down to business:

1. Initialization of greenDao framework (preparation and access)

1.1

// Start with project build:

Dependencies buildscript {repositories {jcenter ()} {the classpath 'com. Android. View the build: gradle: 2.3.3' / / greenDao configuration The classpath 'org. Greenrobot: greendao - gradle - the plugin: 3.2.2'}}Copy the code

1.2

// Configure it in the build of moudle

Apply plugin: 'com.android.application' //greenDao relies on apply Plugin: 'org.greenrobor.greendao' android {........ GreenDao {schemopackage; greenDao {schemopackage 'com. Example. Mysmall. Greendao. Greendao' / / this is preserving the generated code package name targetGenDir 'SRC/main/Java / / save the Java code path dependencies {}} compile fileTree(include: ['*.jar'], dir: 'libs') androidTestCompile (' com. Android. Support. The test. The espresso: espresso - core: 2.2.2', {exclude group: 'com.android.support', module: 'support-annotations' }) ..... / / greenDao configuration the compile 'org. Greenrobot: greenDao: 3.2.2' compile 'org. Greenrobot: greenDao - generator: 3.2.2'}Copy the code

2. Create the entity class and then click Build -> Make Project

Create entity class @generated (hash = 664611791) hash = build->Make Project

@entity Public class User {/** Define primary key */ @ID (Autoincrement = true) private Id; private String name; private int age; private String sex; @Generated(hash = 664611791) public User(long id, String name, int age, String sex) { this.id = id; this.name = name; this.age = age; this.sex = sex; } @Generated(hash = 586692638) public User() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}'; }}Copy the code

Note that the entity class is annotated to map to a database table (so you don’t have to write the sal created by the database yourself); Ok ~ here are the notes: @id Selects a property of type long or long as the primary key of the table in the database corresponding to the Entity. @generated is Generated before the constructor

Build ->Make Project then automatically generates the action classes for the database:



DaoMaster DaoSession UserDao;

Start to operate the database with greenDao :(use log to show the data changes of each operation):

3.1 Database initialization in App(extends Application implementation code):

public class App extends Application{ private UserDao userDao; private static App mApp; @Override public void onCreate() { super.onCreate(); MHelper = new daomaster.devOpenHelper (this, "user-db", null); / / daomaster.devOpenHelper (this, "user-db", null); SQLiteDatabase db = mHelper.getWritableDatabase(); DaoMaster master = new DaoMaster(db); DaoSession daoSession = master.newSession(); userDao = daoSession.getUserDao(); } public static App getInstance(){ if (mApp == null){ synchronized (App.class){ mApp = new App(); } } return mApp; } public UserDao getDao(){ return userDao; }}Copy the code

Core code:

 DaoMaster.DevOpenHelper mHelper = new DaoMaster.
        DevOpenHelper(this, "user-db", null);

        SQLiteDatabase db = mHelper.getWritableDatabase();
        DaoMaster master = new DaoMaster(db);
        DaoSession daoSession = master.newSession();
        userDao = daoSession.getUserDao();Copy the code

3.2 Add, delete, change and check database:

private void initDelete() { //mDao.deleteByKey(Long.valueOf(1)); String trim = mPos.getText().toString().trim(); if (trim ! = null && ! trim.equals("")) { mDao.deleteByKey(Long.valueOf(trim)); QueryBuilder<User> qb = mDao.queryBuilder(); List<User> list = qb.where(UserDao.Properties.Id.eq(Long.valueOf(trim))).list(); If (list.size()<1){toast.maketext (this," specified data deleted successfully ", toast.length_short).show(); } }else { mDao.deleteAll(); } } private void initUpdate() { String trim = mPos.getText().toString().trim(); if (trim ! = null && ! trim.equals("")) { User user = mDao.load(Long.valueOf(trim)); User.setname (" Paul kochagin "); mDao.update(user); } } private void initInsert() { for (int i = 0; i < 5; i++) { mIndex ++; If (isEcho(string.valueof (mIndex))){toast.maketext (this," primary key repeat ", toast.length_short).show(); }else {User User = new User(long.valueof (mIndex), "Long" + I, 18, "male "); mDao.insert(user); } } } private void initSelect() { Query<User> query = mDao.queryBuilder().orderAsc(UserDao.Properties.Id).build(); List<User> list = query.list(); for (int i = 0; i < list.size(); i++) { User user = list.get(i); String s = user.toString(); Log.i("query",s); */ private Boolean isEcho(String id){QueryBuilder<User> qb = mdao.queryBuilder (); List<User> list = qb.where(UserDao.Properties.Id.eq(id)).list(); if (list.size() > 0){ return true; } return false; }Copy the code

Ok ~ from the above code you can see that there is no SQL based operation statement and the resource is automatically switched on and off after each operation, there is no need for you to manually switch the database/cursor/transaction

Is it convenient?

4 Complete code display:

Paste the complete code below:

//app

package com.example.mysmall.greendao.global; import android.app.Application; import android.database.sqlite.SQLiteDatabase; import com.example.mysmall.greendao.greendao.DaoMaster; import com.example.mysmall.greendao.greendao.DaoSession; import com.example.mysmall.greendao.greendao.UserDao; /** * Created by houruixiang on 2017/10/31. */ public class App extends Application{ private UserDao userDao; private static App mApp; @Override public void onCreate() { super.onCreate(); MHelper = new daomaster.devOpenHelper (this, "user-db", null); / / daomaster.devOpenHelper (this, "user-db", null); SQLiteDatabase db = mHelper.getWritableDatabase(); DaoMaster master = new DaoMaster(db); DaoSession daoSession = master.newSession(); userDao = daoSession.getUserDao(); } public static App getInstance(){ if (mApp == null){ synchronized (App.class){ mApp = new App(); } } return mApp; } public UserDao getDao(){ return userDao; }}Copy the code

//MainActivity

package com.example.mysmall.greendao; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.mysmall.greendao.global.App; import com.example.mysmall.greendao.greendao.UserDao; import com.example.mysmall.greendao.model.User; import org.greenrobot.greendao.query.Query; import org.greenrobot.greendao.query.QueryBuilder; import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button mSelect; private Button mInsert; private Button mUpdate; private Button mDelete; private int mIndex; private UserDao mDao; private EditText mPos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MDao = ((App) getApplication()).getDao(); initView(); } private void initView() { mSelect = (Button) findViewById(R.id.seclet); mInsert = (Button) findViewById(R.id.insert); mUpdate = (Button) findViewById(R.id.update); mDelete = (Button) findViewById(R.id.delete); mPos = (EditText) findViewById(R.id.tarPosition); mSelect.setOnClickListener(this); mInsert.setOnClickListener(this); mUpdate.setOnClickListener(this); mDelete.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.seclet: initSelect(); break; case R.id.insert: initInsert(); break; case R.id.update: initUpdate(); break; case R.id.delete: initDelete(); break; } } private void initDelete() { //mDao.deleteByKey(Long.valueOf(1)); String trim = mPos.getText().toString().trim(); if (trim ! = null && ! trim.equals("")) { mDao.deleteByKey(Long.valueOf(trim)); QueryBuilder<User> qb = mDao.queryBuilder(); List<User> list = qb.where(UserDao.Properties.Id.eq(Long.valueOf(trim))).list(); If (list.size()<1){toast.maketext (this," specified data deleted successfully ", toast.length_short).show(); } }else { mDao.deleteAll(); } } private void initUpdate() { String trim = mPos.getText().toString().trim(); if (trim ! = null && ! trim.equals("")) { User user = mDao.load(Long.valueOf(trim)); User.setname (" Paul kochagin "); mDao.update(user); } } private void initInsert() { for (int i = 0; i < 5; i++) { mIndex ++; If (isEcho(string.valueof (mIndex))){toast.maketext (this," primary key repeat ", toast.length_short).show(); }else {User User = new User(long.valueof (mIndex), "Long" + I, 18, "male "); mDao.insert(user); } } } private void initSelect() { Query<User> query = mDao.queryBuilder().orderAsc(UserDao.Properties.Id).build(); List<User> list = query.list(); for (int i = 0; i < list.size(); i++) { User user = list.get(i); String s = user.toString(); Log.i("query",s); */ private Boolean isEcho(String id){QueryBuilder<User> qb = mdao.queryBuilder (); List<User> list = qb.where(UserDao.Properties.Id.eq(id)).list(); if (list.size() > 0){ return true; } return false; }}Copy the code

All in all, Greendao’s framework as the Android database framework will greatly improve efficiency; Interested can explore its internal implementation mechanism ~ thanks for reading the weather turns cold beware of cold oh