GreenDao Fast ORM in Android

Today We are learning about the Green Dao integration in android. It is a fast ORM (Object Relational Mapping) tool for android. Green Dao offers an object oriented interface with  relation database sqlite. It is fast to other ORM that why it is something special and different.
Green dao has two basic things that works. One is core dao and another is Dao Generator. We can use this Core Dao and Dao generator will create automatically by Wrapper.

Green Dao Documentation.

DaoMaster: DaoMaster holds the database object (SQLiteDatabase) and manages DAO classes (not objects) for a specific schema. It has static methods to create the tables or drop them. Its inner classes OpenHelper and DevOpenHelper are SQLiteOpenHelper implementations that create the schema in the SQLite database. 

DaoSession: Manages all available DAO objects for a specific schema, which you can acquire using one of the getter methods. DaoSession provides also some generic persistence methods like insert, load, update, refresh and delete for entities. Lastly, a DaoSession objects also keeps track of an identity scope. 

DAOs: Data access objects (DAOs) persists and queries for entities. For each entity, greenDAO generates a DAO. It has more persistence methods than DaoSession, for example: count, loadAll, and insertInTx.

Entities: Persistable objects. Usually, entities are objects representing a database row using standard Java properties (like a POJO or a JavaBean).


Lets integrate the Green Dao with our small app to test. You need to create the java library with your project. Lava library is a module for your project. Here I have created "GreenDaoGenerator".


build.gradle module level

apply plugin: 'java'

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'org.greenrobot:greendao-generator:3.2.0'

}

sourceCompatibility = "1.7"
targetCompatibility = "1.7"

MainGenerator.java

public class MainGenerator {

    public static void main(String[] args) throws Exception {
        Schema schema = new Schema(3, "com.sunil.greendaorxapp.daogen");
        addNote(schema);
        new DaoGenerator().generateAll(schema, "../GreenDaoRxApp2/app/src/main/java/");
    }

    private static void addNote(Schema schema) {
        Entity note = schema.addEntity("Note");
        note.addIdProperty();
        note.addStringProperty("tittle").notNull();
        note.addStringProperty("comment");
        note.addStringProperty("noteDate");
    }
}



Now you have done your module setting. Whenever you want to change in schema or in any field of your table you need to run this main generator to update dao class.

build.gradle project level

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle app level

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: 'org.greenrobot.greendao'


android {
    compileSdkVersion 24
    buildToolsVersion "24.0.0"
    defaultConfig {
        applicationId "com.sunil.greendaorxapp"
        minSdkVersion 14
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

greendao {
    targetGenDir 'src/main/java'
}


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'
    compile "com.jakewharton:butterknife:8.1.0"
    apt 'com.jakewharton:butterknife-compiler:8.0.1'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile "com.android.support:recyclerview-v7:24.2.0"
    compile "com.android.support:cardview-v7:24.2.0"
    compile 'org.greenrobot:greendao:3.2.0'
    compile 'com.android.support:design:24.2.0'
    compile 'net.zetetic:android-database-sqlcipher:3.5.1'
}

build.gradle project level

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

MainApplication.java

public class MainApplication extends Application{

    private static Context mContext;
    private DaoSession daoSession;
    public static final boolean ENCRYPTED = true;

    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();

        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, ENCRYPTED ? "notes-db-encrypted" : "notes-db");
        Database db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();
        daoSession = new DaoMaster(db).newSession();
    }

    public static Context getAppContext() {
        return mContext;
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }
}



MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static String TAG = MainActivity.class.getSimpleName();

    @BindView(R.id.no_data)
    TextView no_data_tv;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.button_create)
    Button btn_create;


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

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

    }

    @Override
    protected void onResume() {
        super.onResume();

        final List list = NoteManager.loadAll(this);
        if (list == null && list.size() == 0) {
            no_data_tv.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
        } else {
            no_data_tv.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            NoteAdapter adapter = new NoteAdapter(this, list);
            recyclerView.setAdapter(adapter);
            recyclerView.addOnItemTouchListener(
                    new RecyclerItemClickListener(this, new   RecyclerItemClickListener.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {

                            Note note = list.get(position);
                            Intent intent = new Intent(MainActivity.this, NoteDetailActivity.class);
                            intent.putExtra("Create", false);
                            intent.putExtra("NoteID", note.getId());
                            startActivity(intent);
                        }
                    })
            );

        }
    }

    @OnClick(R.id.button_create)
    public void createNoteClick() {
        Intent intent = new Intent(MainActivity.this, NoteDetailActivity.class);
        intent.putExtra("Create", true);
        startActivity(intent);
    }
}


activity_main.xml

<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    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="com.sunil.greendaorxapp.MainActivity">

    <TextView
        android:id="@+id/no_data"
        android:text="@string/no_note"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

   <android.support.v7.widget.RecyclerView
       android:id="@+id/recyclerView"
       android:layout_width="match_parent"
       android:layout_marginBottom="20dp"
       android:layout_height="wrap_content">
   </android.support.v7.widget.RecyclerView>

    <Button
        android:id="@+id/button_create"
        android:layout_alignParentBottom="true"
        android:background="@color/colorAccent"
        android:layout_width="match_parent"
        android:text="@string/Create_Note"
        android:textColor="@color/colorPrimaryDark"
        android:layout_height="wrap_content" />
</RelativeLayout/>

NoteManager.java

public class NoteManager {

    public static Note load(Context ctx, long id) {
        return getNoteDao(ctx).load(id);
    }

    public static List loadAll(Context ctx) {
        return getNoteDao(ctx).loadAll();
    }

    public static long insertOrReplace(Context ctx, Note note) {
        return getNoteDao(ctx).insertOrReplace(note);
    }

    public static void remove(Context ctx, Note note) {
        getNoteDao(ctx).delete(note);
    }

    private static NoteDao getNoteDao(Context c) {
        // get the note DAO
        DaoSession daoSession = ((MainApplication) MainApplication.getAppContext()).getDaoSession();
        NoteDao noteDao = daoSession.getNoteDao();
        return noteDao ;
    }

}


NoteDetailActivity.java

public class NoteDetailActivity extends AppCompatActivity {

    private static String TAG = NoteDetailActivity.class.getSimpleName();

    @BindView(R.id.titleLayout)
    TextInputLayout titleLabelLayout;
    @BindView(R.id.descriptionLayout)
    TextInputLayout descriptionLabelLayout;
    @BindView(R.id.dateLayout)
    TextInputLayout dateLabelLayout;

    @BindView(R.id.title)
    EditText titleEditText;
    @BindView(R.id.description)
    EditText descriptionEditText;
    @BindView(R.id.age)
    EditText dateEditText;

    @BindView(R.id.save)
    Button save;

    private boolean isCreate;
    private Long noteId;
    Note mNote;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note_detail);
        ButterKnife.bind(this);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            isCreate = bundle.getBoolean("Create");
            noteId = bundle.getLong("NoteID");
        }
        if (!isCreate) {
            save.setText("Save");
            mNote = NoteManager.load(this, noteId);
            if (mNote != null) {
                titleEditText.setText(mNote.getTittle());
                descriptionEditText.setText(mNote.getComment());
                dateEditText.setText(mNote.getNoteDate() + "");
            }
        } else {
            save.setText("Add");
            Calendar c = Calendar.getInstance();
            System.out.println("Current time => " + c.getTime());
            dateEditText.setText(c.getTime()+"");
        }
    }

    @OnClick(R.id.save)
    public void saveClick(){
        if (isCreate){
            // insert note
            if (!valid()){
                return;
            }else{
                Note note = new Note();
                note.setTittle(titleEditText.getText().toString());
                note.setComment(descriptionEditText.getText().toString());
                note.setNoteDate(dateEditText.getText().toString());
                NoteManager.insertOrReplace(this, note);
                finish();
            }

        }else{
            // update note
            if (!valid()){
                return;
            }else{
                mNote.setTittle(titleEditText.getText().toString());
                mNote.setComment(descriptionEditText.getText().toString());
                mNote.setNoteDate(dateEditText.getText().toString());
                NoteManager.insertOrReplace(this, mNote);
                finish();
            }
        }
    }

    private boolean valid(){
        boolean isValid;
        if (Utility.nullCheck(titleLabelLayout, "Title")){
            isValid = false;
        }
        else if (Utility.nullCheck(descriptionLabelLayout, "Comment")){
            isValid = false;
        }
        else if (Utility.nullCheck(dateLabelLayout, "Date")){
            isValid = false;
        }else{
            isValid = true;
        }
        return  isValid;
    }
}





Thanks for reading this post. I hope it will helps you.

Comments

  1. Replies
    1. Here is github link
      https://github.com/sunil676/GreenDaoRxApp2

      Delete
  2. where is the other code of the NoteDetailActivity in xml then how get the RecyclerItemClickListener.. or I create the RecyclerItemClickListener java class to get this... then the Utility how to get also.. or maybe you give the whole source code... thank you.. hope you help me...

    ReplyDelete
  3. Hello give me the whole source code of this project.. thank you

    ReplyDelete

Post a Comment

Popular posts from this blog

NavigationView Drawer Expandable menu Item in ANdroid

Service LifeCycle

Custom SeekBar (Discrete SeekBar) in android