In the process of Android development, data storage requirements are often encountered. For simple information, SP (SharedPreferences) can be used to store it. For complex scenarios, such as chat records and network cache, information stored in a database, such as SQLite, is generally needed. In addition to the system’s native database, SQLite, there are some open source databases, such as Greendao.

Greendao adopts the lightweight ORM (Object Relation Mapping) architecture of Android. ORM is to map Java objects to SQLite database. When operating the database, there is no need to write complex SQL statements. It is easy to use objects to store, update, delete and query the database. And Greendao is highly optimized for Android, with low memory overhead, small dependency volume and support for database encryption.




How to addgreenDAOInto the project?

Add the Gradle configuration in the root build.gradle

buildscript { repositories { google() jcenter() mavenCentral() // add repository } dependencies { classpath 'com. Android. Tools. Build: gradle: 3.3.2 rainfall distribution on 10-12' classpath 'org. Greenrobot: greendao - gradle - plugin: 3.3.0' / / add the plugin}}

Add Gradle configuration to app/build.gradle in application modules

apply plugin: 'com.android.application' apply plugin: 'org. Greenrobot. Greendao' / / apply plugin dependencies {implementation 'org. Greenrobot: greendao: 3.3.0' / / the add library}

So far we’ve introduced greendao into the project, where mavenCentral() is configured because greendao exists in the mavenCentral repository, and gradle-plugin is introduced because you can link plug-ins to the project build process. Daomaster, DaoSession, and XXXDAO classes can be generated automatically when the project is built.

Example demonstration, create entity class, generate specific file on the database operation

Create a Chathistory class

@Entity
public class ChatHistory {
    @Id(autoincrement = true)
    private Long id;
    @NotNull
    private String userId;
    @NotNull
    private String content;
    @NotNull
    private String timeStamp;
}

Click Android Studio/Build/Make Project to generate the Chathistory constructor and the get and set methods automatically. The class ChathIStoryDAO, Daomaster, DaoSession is generated in the build/generated directory. If you want to change the generation directory for ChatHistory, DaoMaster, daoSession, you can configure it in the build.gradle file

android {
    GreenDao {
        schemaVersion 1
        daoPackage 'com.ecarx.wechat'
        targetGenDir 'src/main/java'
    }
}

The generated Chathistory, Daomaster, and DaoSession classes can be used to manipulate the database

The generated classes are encapsulated to facilitate manipulation of the database

public class DBManager { private static DBManager instance; private DaoSession mDaoSession; private ChatHistoryDao mChatHistoryDao; public static DBManager getInstance(Context context) { if (instance == null) { synchronized (DBManager.class) { instance  = new DBManager(context); } } return instance; } private DBManager(Context context) { DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(context, "chat.db"); mDaoSession = new DaoMaster(devOpenHelper.getWritableDatabase()).newSession(); mChatHistoryDao = mDaoSession.getChatHistoryDao(); } public void insertChat(Chathistory chat) {try {mChathistoryDao. insert(chat); } catch (Exception e) { e.printStackTrace(); }} public void updateChat(Chathistory chat) {List< Chathistory > ChathistoryList = mChatHistoryDao.queryBuilder().where(ChatHistoryDao.Properties.Id.eq(chat.getId())).list(); if (chatHistoryList ! = null && chatHistoryList.size() > 0) { mChatHistoryDao.update(chatHistoryList.get(0)); }} public List< Chathistory > queryChat(int page, int pageSize, int pageSize, int pageSize) String userId) { List<ChatHistory> chatHistories = new ArrayList<>(); try { QueryBuilder queryBuilder = mChatHistoryDao.queryBuilder(); queryBuilder.where(ChatHistoryDao.Properties.UserId.eq(userId)); queryBuilder.orderDesc(ChatHistoryDao.Properties.Id); queryBuilder.offset((page - 1) * pageSize); queryBuilder.limit(pageSize); chatHistories = queryBuilder.list(); } catch (Exception e) { e.printStackTrace(); } return chatHistories; } public void DeletMessage (int userId) {try {List< Chathistory > Chathistories = mChatHistoryDao.queryBuilder().where(ChatHistoryDao.Properties.UserId.eq(userId)).list(); if (chatHistories ! = null && chatHistories.size() > 0) { mChatHistoryDao.delete((ChatHistory) chatHistories); } } catch (Exception e) { e.printStackTrace(); }}}

Data insertion, query and other operations are realized by encapsulating the class

ChatHistory chatHistory = new ChatHistory(); chatHistory.setUserId("10086"); SetContent (" How about an outing tomorrow "); chatHistory.setTimeStamp("1616135247000"); DBManager dbManager = DBManager.getInstance(this); // insert record dbManager.insertChat(chatHistory); List< Chathistory > List = dbManager.queryChat(1, 15, "10086");
conclusion

Use Greendao in three steps:

  • Construct gradle and introduce greendao and greendao-gradle-plugin
  • Create the entity class and compile it to automatically generate Daomaster, DaoSession and XXXDAO
  • Use generated classes for data manipulation