GreenDao Android Studio

2019-01-21 22:04发布

问题:

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!

回答1:

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.



回答2:

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.

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

In build.gradle of Module:app, insert

compile 'de.greenrobot:greendao:2.1.0'

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

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

Make sure, you sync your project.

  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

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

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.

  2. Now Run it.

PART 3 – VIEW THE SQL DB

  1. Open Command Prompt.
  2. Enter the following commands.

  3. Opening the db file in SQLite3

  4. Using SQLite3

PART 4 – EXTRAS

  1. Structure (Core Classes) of GREENDAO



回答3:

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



回答4:

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'
    }
}


回答5:

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.



回答6:

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.