GreenDao Android Studio

前端 未结 6 929
臣服心动
臣服心动 2020-12-13 18:19

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

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 18:56

    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.

      
      
      

    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_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

提交回复
热议问题