Android database connection using greenDAO library

greenDAO : Android ORM (Object/Relational Mapping) for SQLite database.

In Android, while dealing with big data projects we may require storing data locally. So very first thing comes in mind is SQLite.

But it may be complex to write SQL query for each transaction and it can be time-consuming.

Here is a simple solution to deal with android local database, greenDAO.

greenDAO is an object/relational mapping (ORM) tool for Android. It offers an object-oriented interface to the relational database SQLite.

Simple Guide:

Here are quick steps to start using greenDAO in our Android projects.

Add below dependencies into build.gradle(Module: app) file

apply plugin: 'org.greenrobot.greendao'

dependencies {

compile 'org.greenrobot:greendao-generator:3.2.0'
compile 'org.greenrobot:greendao:3.2.0'

}

And below code in build.gradle(Project: projectName) file

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
    }
}

Let’s create a class which will handle the database creation, say DbMain.java. For better understanding, we will create a commonly used table, Users table.

public class DbMain {
    public static void main(String args[]) throws Exception {
        Schema schema = new Schema(1, 
                             "your_package_name_goes_here");

        Entity users = schema.addEntity("Users");
        users.addLongProperty("Id")
             .primaryKey()
             .autoincrement();
        users.addStringProperty("Name");
        users.addLongProperty("Phone").unique();

        DaoGenerator daoGenerator = new DaoGenerator();
        daoGenerator.generateAll(schema, "./app/src/main/java");
    }
}

Here, Schema class constructor has two parameters version and package_name. Whenever you change the database structure, add/delete/update table or table columns, you will need to increment the version by 1 and run this DbMain.java class.

 

How to create a table using greenDao?

Very simple, use Entity class, provide the table name in addEntity(table_name) method as a parameter, this will automatically create a table for you. Use the instance of it to add columns in the table. You can update it anytime, just remember to increment the version value by 1.

Entity users = schema.addEntity("Users");

The class DbMain.java not only creates a table but also it generates few more classes automatically.

  • DaoMaster.java: This class has the operations for the overall database. It is Auto Generated by greenDao and don’t edit this class.
  • DaoSession.java: This class creates a session for each table. It is Auto Generated by greenDao and don’t edit this class.
  • UsersDao.java: For each table, there is a separate Dao class which will operate only on the table. It is Auto Generated by greenDao and don’t edit this class.
  • Users.java: This is just a model class (POJO class), which helps to bind the data to operate on the table. It is Auto Generated by greenDao and don’t edit this class.

 

How to run the DbMain.java class?

Right click on DbMain.java class, click on Run “DbMain.main()” or simply press ctrl+shift+F10. By running this class means, recreating the data structure. Refer below screen shots for quick understanding.

android_db

android_db1

Now, whenever you click on Run button in the toolbar, you might end up with running DbMain.java class each time. You will need to change Run Configuration to run your application.

Go to Run —> Edit Configurations —> from left panel select Android App —> app folder —> click on Ok. That’s it!

android_db2

android_db3

Now click on Run button, you will be able to run your project’s default configuration.

Till now we just created an environment to play and now it’s time to play!

CURD using greenDao

Create a data entry in a table.

 DaoSession daoSession = AppController.getInstance()
                                      .getDaoMaster()
                                      .newSession();
 UsersDao usersDao = daoSession.getUsersDao();
 Users user = new Users();
 user.setName("Qice");                   
 user.setPhone(9000000000);
 usersDao.insert(user); //This will add a row in the Users table.

Update data entry in a table.

 DaoSession daoSession = AppController.getInstance().getDaoMaster().newSession();
 
 UsersDao usersDao = daoSession.getUsersDao();
 try{
     User> user = usersDao.queryBuilder()
                      .where(UsersDao.Properties.Id.eq(1))
                      .uniqueOrThrow();

     user.setName("Qice Technologies");
     user.setPhone(9000000001);
     usersDao.update(user); // this line will update the data

 } catch(Exception e) {
  //catch the exception, if there is no row available for the id.
 }

Read the data from a table.

 DaoSession daoSession = AppController.getInstance()
                                      .getDaoMaster()
                                      .newSession();
 UsersDao usersDao = daoSession.getUsersDao();

 List<Users> users =  usersDao.queryBuilder().list(); 

 // This line gets all the row from the table, 
 //you can add  where clause to add constraints.

Delete data entry from a table.

DaoSession daoSession = AppController.getInstance().getDaoMaster().newSession();
 
 UsersDao usersDao = daoSession.getUsersDao();
 try{
 User> user = usersDao.queryBuilder()
                      .where(UsersDao.Properties.Id.eq(1))
                      .uniqueOrThrow();

 usersDao.delete(user); //this line will delete the data entry for the id.

 } catch(Exception e) {
    // catch the exception, if there is no row available for the id.
 }

You can find a complete sample of the Android project using greenDao in our GitHub repository.

 

Do’s and Don’ts for Android Apps

There are few things most of the new android developers face. To avoid these issues while developing one should be following best practices to improve the functionality of the android app and to attain optimum results.

Do’s  for Android App Development

  • Prefer ConstraintLayout while making designs in xml file of android. It is more flexible. If necessary, look for others.
  • Give meaningful id name for each view in xml. For example, If you are using EditText for username and password then their names should be editTextUsername and editTextPassword.
  • If any group of views is repeatable in more than one xml file, make a different file with that group of views and include it where you want. Eg. <include layout=“@layout/toolbar”/> : toolbar is a different layout which has the design for common toolbar used in the app.
  • Write all the texts, used in the app, in string.xml file and give reference of that string in layout xml file. Also, all the messages should be defined in string.xml file. Later on, it will be easier to modify it.
  • Write all the dimensions, used in the app, in dimen.xml file and give reference of that dimensions in layout xml file.
  • Write all the colors, used in the app, in color.xml file and give reference of that color in layout xml file.
  • Try using style.xml file for custom view design instead of doing it programmatically.
  • All constants should be declared in separate java file say, Constants.java, Each constant should be static(it will allocate memory only one time and can be reusable) and final(not changeable).
  • Define all commonly used methods in one class say, Utils.java.
  • If code lines are exceeding 15-20 lines, put the code in a method.
  • The naming of variables, objects, methods, classes, interfaces, etc should be self-explanatory.
  • It’s better to write a separate class for any reusable functionality.
  • Project code should be divided into different modules. According to the module, you can put the java files in different packages under the main package.
  • The module can be Login, DrawerItems (if an app has the drawer, list out all the main files of drawer items), etc.. and it will depend on the project’s features.
  • Use fragment, if you want to show more than one screen in single Activity. A fragment is nothing but the part, part of design. It is totally dependent on Activity.
  • Interfaces can be used to pass the data of one class to other class(it can be Activity, Fragment, Service, or simple Java class) on any triggered event.
  • Service: It is used as a background task. Eg. To do network call, to play music in the background, etc.
  • Use Glide/Picasso library to load image URLs.
  • Use Retrofit library to make network calls. See this blog how to use it in android.
  • Use GreenDAO library to do local database transactions.
  • Use Genymotion virtual device to run the android app.
  • You can use Testfairy to distribute your android app remotely.

 

Similarly, you should know what are bad practices in android development, what to avoid while developing an android app. Below are some points developers should avoid.

Don’ts for Android App Development

  • Try to avoid using Relative layout, if it is not necessary.
  • Avoid using nested Linear layout it affects the UI performance.
  • Never use ‘my’ prefix in naming conventions. Also never use shortcut names. Eg tvNm, etPwd, etc.
  • Your code length for a class should not exceed 1000 lines. If possible try to add a supporting class.
  • Avoid using hard-coded values in Activity/Fragment as much as possible.
  • Avoid using libraries as a project module, instead, add dependencies in build.gradle file of app Module of the project.
  • Don’t use too many libraries.