How to use GreenDao in android studio?

Here you will learn, how to integrate GreenDao with android studio. GreenDao is used for accessing local sql database into your android application. We will be creating a log app, that saves user text in the database.Lets get started. If you have any confusions, please feel free to download the entire project.

[wpi_designer_button text=’Download’ link=’https://github.com/arjunsk/greendao_example’ style_id=’48’ icon=’github’ target=’_blank’]

STEPS:

PART1 : Setting Up GREENDAO

  1. Create an android project.
  2. Click File >New > New Module. Select Java Library and click Next.
    Greendao
  3. Now we have to add the following Gradle Dependencies.In build.gradle of Module:app, insert
    compile 'de.greenrobot:greendao:2.1.0'

    2
    In the build.gradle of  Module:greendao-generator, insert

    compile 'de.greenrobot:greendao-generator:2.1.0'

    3
    Make sure, you sync your project.
    4

  4. Now in the MainGenerator.java, we will define the database structure.
    import de.greenrobot.daogenerator.DaoGenerator;
    import de.greenrobot.daogenerator.Entity;
    import de.greenrobot.daogenerator.Schema;
    
    public class MainGenerator {
        public static void main(String[] args)  throws Exception {
    
            //place where db folder will be created inside the project folder
            Schema schema = new Schema(1,"com.codekrypt.greendao.db");
    
            //Entity i.e. Class to be stored in the database // ie table LOG
            Entity word_entity= schema.addEntity("LOG");
            
            word_entity.addIdProperty(); //It is the primary key for uniquely identifying a row
            
            word_entity.addStringProperty("text").notNull();  //Not null is SQL constrain
            
            //  ./app/src/main/java/   ----   com/codekrypt/greendao/db is the full path
            new DaoGenerator().generateAll(schema, "./app/src/main/java");
    
        }
    }
    
  5. Run MainGenerator.java .5
  6. After running this, you will observe a newly created folder ie db in the Main Project Folder.
    6

PART2 : Integrating it with Android Project

  1. Set the activity_main.xml layout.
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="com.codekrypt.greendao.MainActivity">
    
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textData"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true" />
    
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Save"
            android:id="@+id/textSave"
            android:layout_below="@+id/textData"
            android:layout_alignEnd="@+id/textData"
            android:layout_marginTop="22dp" />
    
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Show Top"
            android:id="@+id/textTop"
            android:layout_below="@+id/textSave"
            android:layout_alignParentStart="true"
            android:layout_marginTop="35dp" />
    </RelativeLayout>
    
  2. In MainActivity.java

    package com.codekrypt.greendao;
    
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    
    import com.codekrypt.greendao.db.DaoMaster;
    import com.codekrypt.greendao.db.DaoSession;
    import com.codekrypt.greendao.db.LOG;
    import com.codekrypt.greendao.db.LOGDao;
    
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
    
        //Dao --> Data Access Object
        private LOGDao log_dao; // Sql access object
        private LOG temp_log_object; // Used for creating a LOG Object
    
        String log_text="";  //Entered text data is save in this variable
    
        private  final String DB_NAME ="logs-db" ;  //Name of Db file in the Device
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            //Initialise DAO
            log_dao=setupDb();
    
            //Setting up form elements
            Button textSave= (Button) findViewById(R.id.textSave);
            Button textTop= (Button) findViewById(R.id.textTop);
            final TextView textData=(TextView) findViewById(R.id.textData);
    
            assert textSave != null;
            textSave.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    log_text=textData.getText().toString();
                    temp_log_object=new LOG(null,log_text);// Class Object, Id is auto increment
    
                    SaveToSQL(temp_log_object);
                }
            });
    
            assert textTop != null;
            textTop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    textData.setText( getFromSQL() );
                }
            });
        }
    
        //---------------------------------SQL QUERY Functions-----------------------------------------//
        public String getFromSQL(){
            List<LOG> log_list = log_dao.queryBuilder().orderDesc(LOGDao.Properties.Id).build().list();  
            //Get the list of all LOGS in Database in descending order
            
            if(log_list.size()>0) {  //if list is not null
    
                return log_list.get(0).getText();
                //get(0)--> 1st object
                // getText() is the function in LOG class
            }
            return "";
        }
    
        public void SaveToSQL(LOG log_object) {
            log_dao.insert(log_object);
        }
        //----------------------------***END SQL QUERY***---------------------------------------------//
    
    
        //-------------------------------DB Setup Functions---------------------------------------------//
    
        //Return the Configured LogDao Object
        public LOGDao setupDb(){
            DaoMaster.DevOpenHelper masterHelper = new DaoMaster.DevOpenHelper(this, DB_NAME, null); //create database db file if not exist
            SQLiteDatabase db = masterHelper.getWritableDatabase();  //get the created database db file
            DaoMaster master = new DaoMaster(db);//create masterDao
            DaoSession masterSession=master.newSession(); //Creates Session session
            return masterSession.getLOGDao();
        }
        //-------------------------***END DB setup Functions***---------------------------------------//
    
    }
    
  3. Before Running the App, Make sure you have changed your configuration.
    7
  4. Now Run it.

PART 3 – VIEW THE SQL DB

  1. Open Command Prompt.
  2. Enter the following commands.
    8
  3. Opening the db file in SQLite3
    9
  4. Using SQLite3
    10

PART 4 – EXTRAS

  1. Structure (Core Classes) of GREENDAO
    Core-Classes-150

3 thoughts on “How to use GreenDao in android studio?

  1. Greate tutorials 🙂
    Please provide details or tutorial while working on external/prepopulated database which is present on assets folder.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s