Green Dao

Android GreenDAO Example

There are two step required for implementing Green Dao ORM library in to android project

1. Create generator java module
2. Implement data base interaction in Activity

Step 1. Create generator java module

The generator module contains a single class containing the data model definition. This will automatically generate model class and Dao calss for the database interaction

How to create a generator module?

In android studio got File->New-> New Module select Java Library 

javalib

Give library name and class name

javalib2

After adding the library the folder structure will be like this

befouremoduleexe

add GreenDao dependency in the created module, and sync

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

for Green dao 3.x please use the plugin

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

generatergradile

Add the following code in GeneratorClass.java file. Here we defining a users table scema

import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Schema;

public class GeneratorClass {

    public static void main(String[] args)  throws Exception {

        //place where db folder will be created inside the project folder
        Schema schema = new Schema(1,"samples.bm.com.greendaoe1.db");

        //Entity Users or table Users
        Entity user= schema.addEntity("Users");
        user.addIdProperty();                       //It is the primary key for uniquely identifying a row
        user.addStringProperty("name").notNull();    //Not null is SQL constrain
        user.addStringProperty("email");
        user.addStringProperty("password");
        //user.addDateProperty("date");

        //  ./app/src/main/java/   ----   com/codekrypt/greendao/db is the full path
        new DaoGenerator().generateAll(schema, "./app/src/main/java");
    }
}

for Green dao 3.x:- just change the imports

import org.greenrobot.greendao.generator.DaoGenerator;
import org.greenrobot.greendao.generator.Entity;
import org.greenrobot.greendao.generator.Schema;

Run GeneratorClass.java file

rungenerator

It will Create a db folder inside out main app package

aftermoduleexe

 

2. Implement data base interaction in Activity

Add Green Dao gradle dependency in our main project and sync

compile 'de.greenrobot:greendao:2.1.0'

for Green dao 3.x:-

compile 'org.greenrobot:greendao:3.1.1'

appgradle

MainActivity .java

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import samples.bm.com.greendaoe1.db.DaoMaster;
import samples.bm.com.greendaoe1.db.DaoSession;
import samples.bm.com.greendaoe1.db.Users;
import samples.bm.com.greendaoe1.db.UsersDao;


public class MainActivity extends AppCompatActivity {

    //Dao --> Data Access Object
    private UsersDao userDao; // Sql access object

    private final String DB_NAME = "my-app-db";  //Name of Db file in the Device

    EditText mEtName;
    EditText mEtEmail;
    EditText mEtPassword;

    ArrayAdapter<String> mAdapter;
    ListView mListView;

    List<String> mResult = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Initialise DAO
        userDao = setupDb();

        //Setting up form elements
        Button btnSave = (Button) findViewById(R.id.btn_Save);

        mEtName = (EditText) findViewById(R.id.et_name);
        mEtEmail = (EditText) findViewById(R.id.et_email);
        mEtPassword = (EditText) findViewById(R.id.et_password);

        mListView = (ListView) findViewById(R.id.lv_result);

        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, mResult);
        mListView.setAdapter(mAdapter);

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String name = mEtName.getText().toString();
                String email = mEtEmail.getText().toString();
                String password = mEtPassword.getText().toString();

                Users user = new Users(null, name, email, password);// Class Object, Id is auto increment

                SaveToSQL(user);

                generateResult();

                mEtName.setText("");
                mEtEmail.setText("");
                mEtPassword.setText("");
            }
        });

        generateResult();
    }

    private void generateResult() {
        List<Users> usersList = getFromSQL();
        int size = usersList.size();

        if (size > 0) {
            mResult.clear();

            for (int i = 0; i < size; i++) {
                Users currentItem = usersList.get(i);
                mResult.add (0,currentItem.getId() + ", " + currentItem.getName() + ", " + currentItem.getEmail() + ", " + currentItem.getPassword());
            }

            ((BaseAdapter) mListView.getAdapter()).notifyDataSetChanged();
        }
    }


    //---------------------------------SQL QUERY Functions-----------------------------------------//
    public List<Users> getFromSQL() {
        List<Users> userses = userDao.queryBuilder().orderDesc(UsersDao.Properties.Id).build().list();
        return userses;
    }

    public void SaveToSQL(Users user) {
        userDao.insert(user);
    }
    //----------------------------***END SQL QUERY***---------------------------------------------//


    //-------------------------------DB Setup Functions---------------------------------------------//

    //Return the Configured LogDao Object
    public UsersDao 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.getUsersDao();
    }
    //-------------------------***END DB setup Functions***---------------------------------------//

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="samples.bm.com.greendaoe1.MainActivity">


    <EditText
        android:id="@+id/et_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Name" />

    <EditText
        android:id="@+id/et_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Email" />

    <EditText
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password" />

    <Button
        android:id="@+id/btn_Save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"

        android:layout_marginTop="20dp"
        android:text="Result"
        android:textStyle="bold" />

    <ListView
        android:id="@+id/lv_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Out Put

greendaooutput

 

Note:-

While running you app you need to set app from tine toolbar and run

note

 

Ref:

http://greenrobot.org/greendao/

By bm on September 28, 2016 | Android | A comment?
Tags: , ,