GreenDao Android Studio
Asked Answered
T

6

35

I'm looking for a clear step-by-step explanation on how to import GreenDao in Android Studio.

I've used it before in AS, but failed to get it to work again. There are some tutorials out there, but they don't seem to apply to the latest version of AS.

When I clone from github, I get a example project stuff etc. Is there a way to install GreenDaoGenerator without these extras?

Just looking for an up-to-date step-by-step explanation.

Update: I suggest using Realm.io now! Check it out! :-)

Any help would be appreciated!

Tartuffe answered 17/9, 2014 at 10:17 Comment(5)
What about this one: blog.surecase.eu/using-greendao-with-android-studio-ideXylophagous
Seems to skip about 20 steps and the names don't match up.Microgamete
Almost 2 years later and there is still no decent or up-to-date guide to start from scratch!Confab
This sample will help you wiki.workassis.com/android-greendao-exampleQuirita
I wrote a 8 step how to integrate greenDao in Android Studio here akinsete.github.io/articles/2017-01/…Ockham
I
47

Tested on Android Studio 2.0

With Android Studio 0.6.1+ (and possibly earlier) you can easily add non android project to your android project as a module.

Using below method you can have Java modules(greenDaoGenerator) and Android modules in the same project and also have the ability to compile and run Java modules as stand alone Java projects.

  1. Open your Android project in Android Studio. If you do not have one, create one.
  2. Click File > New Module. Select Java Library and click Next.
  3. Fill in the package name, etc and click Finish. You should now see a Java module inside your Android project.
  4. Open the build.gradle file of the java project and add the following dependency

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile('de.greenrobot:DaoGenerator:1.3.0')
    }
    
  5. Copy your DaoGenerator classes or create if you don't have one to your java module.For e.g. I have created ExampleDaoGenerator class in my java module.

    public class ExampleDaoGenerator {
    
        public static void main(String[] args) throws Exception {
            Schema schema = new Schema(1000, "de.greenrobot.daoexample");
            addNote(schema);
            new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");
        }
    
        private static void addNote(Schema schema) {
            Entity note = schema.addEntity("Note");
            note.addIdProperty();
            note.addStringProperty("text").notNull();
            note.addStringProperty("comment");
            note.addDateProperty("date");
       }
    
    }
    

Now, to generate the classes that you can use in android project follow below steps.

  1. Click on the run menu in the top bar. Click Edit Configurations...
  2. In the new window, click on the plus sign at the top left of the window and select Application
  3. A new application configuration should appear, fill the following information.

    1. Give it a name e.g. greenDao.
    2. In main class click … button and select your generator class which have the main method.for e.g. in this case it is com.greendao.generator.ExampleDaoGenerator
    3. In working directory select path of your java project.
    4. In use class of module select you java project. click ok.
    5. Again go to run menu and now you can see e.g. run greendao. click on it.It should compile successfully.

Its done !!! you can check your generated classes in the folder that you have specified.For e.g. in this case it is /DaoExample/src-gen

NOTE: You can run your android project again by clicking on run menu -> Edit Configuration . select your project and click ok.

Indolence answered 8/12, 2014 at 10:49 Comment(7)
Add the dependencies to the java project I want to add greenDAO to or the module I just created? Where does the generator come from and does it matter where in the module I put it?Microgamete
For your first question,the module is the java module itself.So you should add the dependencies to that only.And also let me clear it that this solution is for GreenDaoGeneretor.It will generate classes that one can use in android project.Indolence
You have to add compile('de.greenrobot:greendao:1.3.7') in build.gradle file of your Android project.Xylophagous
It gives me this error: Exception in thread "main" java.io.IOException: ../app/src-gen does not exist. This check is to prevent accidential file generation into a wrong path. any idea how I can fix this ? ThanksDriggers
I fixed that by adding manually the directory src-gen under app module.Driggers
Main step #3, can also be created automatically by selecting your java class, doing right click and selecting run java class.Venison
I wrote a 8 step how to integrate greenDao in Android Studio here akinsete.github.io/articles/2017-01/…Ockham
Z
4

Here's a step by step overview for Integrating GreenDao into your Android Project.

[ Reference How to use GeenDao with Android ? ]

[Project Link: GreenDao Example ]

PART1 : Setting Up GREENDAO

  1. Create an android project.

  2. Click File >New > New Module. Select Java Library and click Next.

Img 1

  1. Now we have to add the following Gradle Dependencies.

In build.gradle of Module:app, insert

compile 'de.greenrobot:greendao:2.1.0'

Img 2

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

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

Img 3

Make sure, you sync your project.

Img 4

  1. 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");

    }
}
  1. Run MainGenerator.java

enter image description here

  1. After running this, you will observe a newly created folder i.e. db in the Main Project Folder.

enter image description here

PART2 : Integrating it with Android Project

  1. Set the activity_main.xml layout.

    <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" />
    

  2. In MainActivity.java,

Add the following codes

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***---------------------------------------//

}
  1. Before Running the App, Make sure you have changed your configuration. enter image description here

  2. Now Run it.

PART 3 – VIEW THE SQL DB

  1. Open Command Prompt.
  2. Enter the following commands. enter image description here

  3. Opening the db file in SQLite3 enter image description here

  4. Using SQLite3 enter image description here

PART 4 – EXTRAS

  1. Structure (Core Classes) of GREENDAO

enter image description here

Zulazulch answered 29/9, 2016 at 14:34 Comment(2)
Does this apply for GreenDAO 3?Rhombus
I wrote a 8 step how to integrate greenDao in Android Studio here akinsete.github.io/articles/2017-01/…Ockham
X
2

I have used this tutorial for Android Studio 0.8.9 and everything works fine.

Xylophagous answered 23/9, 2014 at 22:6 Comment(3)
link is not active now. Please give me the active oneRadon
you are right, but I gave this answer before the accepted one so I guess there is no problem ;)Xylophagous
I wrote a 8 step how to integrate greenDao in Android Studio here akinsete.github.io/articles/2017-01/…Ockham
V
2

Works on Android 1.3 Preview

For the top answer ( Tested on Android Studio 1.0 ), you might need to include that source folder in your project. Go to app/build.gradle

add the following inside android block

sourceSets{

main{
    java{
        srcDir 'src-gen'
    }
}
Venison answered 22/6, 2015 at 0:59 Comment(0)
D
1

Solution: IO-Exception

  1. Go to the build from your dao generator.
  2. add: apply 'application'
  3. add: mainClassName = "you.package.include.Main"
  4. execute "run" in application task (gradle task)

I dont know why it doesnt work when you create manually a run configuration.

Darbies answered 21/3, 2016 at 11:51 Comment(0)
P
0

Basically, what you need is to add a Java library module (File > New > New module..) to your Android project (assuming you're using Android Studio), and insert the generation code inside public static void main(String[] args) {} in this module's .java class. Then Run it and the code will be generated in you main app's module.

See this blog post for a step by step tutorial with explanation.

Pennsylvania answered 1/2, 2016 at 19:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.