[Android] Greendao (1)--project configuration

Source: Internet
Author: User

Project configuration
    • Grdle Configuration

      Gradle with Android Studio

      Compile ' de.greenrobot:greendao:1.3.7 '
      Compile ' de.greenrobot:greendao-generator:1.3.1 '

    • Project configuration

Note that Src-gen is a new folder that we use to put Greendao generated files

Before completing this step, Src-gen is an empty folder, we need to create a new package , create a new Java file under the package, and do the initialization work.
, I created a package called ' com.usst.chensl.introducdemo.db ', and a Java file called ' Exampledaogenerator '.

ExampleDaoGeneratorFile as follows

Package Com.usst.chensl.introducdemo.db;import De.greenrobot.daogenerator.daogenerator;import De.greenrobot.daogenerator.entity;import de.greenrobot.daogenerator.schema;/** * Initialization work * Created by ChenSL on 2015/8/ */public class Exampledaogenerator {private static void Addtaskdetail (schema Schema) {//Specify entity class Entit        Y entity = schema.addentity ("User");        Add id attribute entity.addidproperty ();        Add the column userId, specify non-null, and the default can be null entity.addstringproperty ("UserId"). Notnull ();        Add column username Entity.addstringproperty ("username");        Add Column Age Entity.addintproperty ("age");    Add Column phone Entity.addstringproperty ("phone");  } public static void Main (string[] args) throws Exception {//The first parameter is the database version number, the second parameter is the package name of the schema schema = new        Schema (1, "com.usst.chensl.introductdemo.db");        Adddetail (schema); The try {///second parameter is the new empty folder Sec-gen, which uses the relative path notation//'. ' Represents the previous directory of the project, followed by the project name/app (Androidstudio generation)/SRC-gen (self-built) new Daogenerator (). Generateall (Schema, "...        /introducdemo/app/src-gen ");        } catch (Exception e) {e.printstacktrace (); }    }}

Entity can be considered as a table, it is designed using the constructor pattern, you can specify a column of various database properties, such as non-empty, self-increment, ascending order, primary key and so on.

Note: You must use the run main () method, right-click on the file directly under Androidstudio to select Run Main (), before the LZ tried to run in OnCreate () results error

Here's a look at what's initialized:

  • The user entity class, which has been described as Greendao auto-generated. It's just like building an entity class, but now it's automatically generated by the code.

    Package com.usst.chensl.introductdemo.db;//The This CODE was GENERATED by Greendao, does not EDIT. Enable "Keep" sections if you want to edit. /** * Entity mapped to table USER.    */public class User {private Long ID;    Private String userId;    Private String username;    Private String age;    Private String phone;    Public user () {} public user (Long id) {this.id = ID;        The public User (Long ID, string userId, String username, string age, String phone) {this.id = ID;        This.userid = userId;        This.username = Username;        This.age = age;    This.phone = phone;    } public Long GetId () {return id;    } public void SetId (Long id) {this.id = ID;    } public String GetUserId () {return userId;    } public void Setuserid (String userId) {this.userid = UserId;    } public String GetUserName () {return username;    } public void Setusername (String username) {this.username = username; }   Public String Getage () {return age;    public void Setage (String age) {this.age = age;    } public String Getphone () {return phone;    } public void Setphone (String phone) {this.phone = phone; }}
  • Userdao, if you implement a simple ORM framework, it is easy to see that this is the SQL statement wrapper, there is createtable () , droptable , Readentity , Updatekeyafterinsert , methods of these words too literally

    Package Com.usst.chensl.introductdemo.db;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqlitestatement;import De.greenrobot.dao.abstractdao;import De.greenrobot.dao.property;import De.greenrobot.dao.internal.DaoConfig; Import com.usst.chensl.introductdemo.db.user;//This CODE was GENERATED by Greendao, does not edit./** * DAO for table User.    */public class Userdao extends Abstractdao<user, long> {public static final String TABLENAME = "User";    /** * Properties of entity user.<br/> * Can is used for QueryBuilder and for referencing column names. */public static class Properties {//Parameters are (number of columns, type, variable name of Java entity class, whether primary key, database column name)//because it has entity.addidproperty (), the        To automatically generate the primary key ' _id ' public final static Property id = new Property (0, Long.class, "id", True, "_id");        Public final static Property UserId = new Property (1, String.class, "UserId", False, "user_id"); Public final static ProperTy Username = new Property (2, String.class, "Username", False, "Username");        Public final static Property Age = new Property (3, String.class, ' age ', false, "age");    Public final static Property Phone = new Property (4, String.class, "phone", false, "phone");    };    Public Userdao (daoconfig config) {super (config);    } public Userdao (daoconfig config, daosession daosession) {Super (config, daosession); }/** creates the underlying database table. */public static void CreateTable (Sqlitedatabase db, Boolean ifnotexists) {String constraint = ifnotexists?        "IF not EXISTS": "";                Db.execsql ("CREATE TABLE" + constraint + "' USER ' (" +//"' _id ' INTEGER PRIMARY KEY," +//0:id "' user_id ' text," +//1:userid "' USERNAME ' text," +//2:username "' Age ' text," + 3:age "' PHONE ' TEXT);"); 4:phone}/** Drops the underlying database table. */Public STAtic void Droptable (Sqlitedatabase db, Boolean ifexists) {String sql = "DROP TABLE" + (ifexists? ")        IF EXISTS ":") + "' USER '";    Db.execsql (SQL); }/** @inheritdoc */@Override protected void Bindvalues (Sqlitestatement stmt, User entity) {Stmt.clearbi        Ndings ();        Long id = entity.getid ();        if (id! = NULL) {Stmt.bindlong (1, id);        } String userId = Entity.getuserid ();        if (UserID = null) {stmt.bindstring (2, UserID);        } String username = Entity.getusername ();        if (username! = null) {stmt.bindstring (3, username);        } String Age = Entity.getage ();        if (age! = null) {stmt.bindstring (4, age);        } String phone = Entity.getphone ();        if (phone! = null) {stmt.bindstring (5, phone); }}/** @inheritdoc */@Override public Long readKey (cursor cursor, int offset) {return Cursor.isnull ( Offset + 0)?    Null:cursor.getLong (offset + 0); }/** @inheritdoc */@Override public User readentity (cursor cursor, int offset) {User entity = new U Ser (//cursor.isnull (offset + 0)? Null:cursor.getLong (offset + 0),//ID cursor.isnull (offset + 1)? Null:cursor.getString (offset + 1),//UserId Cursor.isnull (offset + 2)? Null:cursor.getString (offset + 2),//username Cursor.isnull (offset + 3)? Null:cursor.getString (offset + 3),//Age Cursor.isnull (offset + 4)?        Null:cursor.getString (offset + 4)//Phone);    return entity; }/** @inheritdoc */@Override public void readentity (cursor cursor, User entity, int offset) {Entity.set        Id (cursor.isnull (offset + 0)? Null:cursor.getLong (offset + 0));        Entity.setuserid (Cursor.isnull (offset + 1)? null:cursor.getString (offset + 1));    Entity.setusername (Cursor.isnull (offset + 2)? null:cursor.getString (offset + 2));    Entity.setage (Cursor.isnull (offset + 3)? null:cursor.getString (offset + 3));     Entity.setphone (Cursor.isnull (offset + 4)? null:cursor.getString (offset + 4)); }/** @inheritdoc */@Override protected long Updatekeyafterinsert (User entity, long rowId) {Entity.setid        (ROWID);    return rowId; }/** @inheritdoc */@Override public Long GetKey (User entity) {if (entity! = null) {return EN        Tity.getid ();        } else {return null;    }}/** @inheritdoc */@Override protected Boolean isentityupdateable () {return true; }}
  • Daosession, database session

    Package Com.usst.chensl.introductdemo.db;import Android.database.sqlite.sqlitedatabase;import Java.util.Map; Import De.greenrobot.dao.abstractdao;import De.greenrobot.dao.abstractdaosession;import De.greenrobot.dao.identityscope.identityscopetype;import De.greenrobot.dao.internal.daoconfig;import Com.usst.chensl.introductdemo.db.user;import com.usst.chensl.introductdemo.db.userdao;//This CODE was GENERATED by  Greendao, do not edit./** * {@inheritDoc} * * @see de.greenrobot.dao.AbstractDaoSession */public class Daosession extends    abstractdaosession {private final daoconfig userdaoconfig;    Private final Userdao Userdao; Public daosession (Sqlitedatabase db, Identityscopetype type, map<class<? extends abstractdao<?,? >>        Daoconfig> Daoconfigmap) {super (db);        Userdaoconfig = Daoconfigmap.get (Userdao.class). Clone ();        Userdaoconfig.initidentityscope (type);        Userdao = new Userdao (userdaoconfig, this); Registerdao (User.class, Userdao);    public void Clear () {Userdaoconfig.getidentityscope (). Clear ();    } public Userdao Getuserdao () {return userdao; }}
  • Daomaster, encapsulation of sqlitedatabase , containing Userdao

    Package Com.usst.chensl.introductdemo.db;import Android.content.context;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqlitedatabase.cursorfactory;import Android.database.sqlite.sqliteopenhelper;import Android.util.log;import De.greenrobot.dao.AbstractDaoMaster; Import De.greenrobot.dao.identityscope.identityscopetype;import com.usst.chensl.introductdemo.db.userdao;//This CODE is GENERATED by Greendao, does not edit./** * Master of DAO (schema version 1): Knows all Daos.*/public class Daomaste    R extends Abstractdaomaster {public static final int schema_version = 1; /** creates underlying database table using DAOs. */public static void Createalltables (Sqlitedatabase db, Boolean ifnotexists) {userdao.createtable (db, Ifnotexi    STS); }/** Drops underlying database table using DAOs.    */public static void Dropalltables (Sqlitedatabase db, Boolean ifexists) {userdao.droptable (db, ifexists); }//abstract class public static abstractClass Openhelper extends Sqliteopenhelper {public Openhelper (context context, String name, Cursorfactory Factory)        {Super (context, name, Factory, Schema_version); } @Override public void OnCreate (Sqlitedatabase db) {log.i ("Greendao", "Creating tables for Sche            Ma version "+ schema_version);        Createalltables (db, false); }}//Real implementation class/** warning:drops all table on upgrade! Use only during development. */public static class Devopenhelper extends Openhelper {public Devopenhelper (context context, String name, Cur        Sorfactory factory) {Super (context, name, factory); } @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {LOG.I ("GRE            Endao ', ' Upgrading schema from version ' + oldversion + ' to ' + NewVersion + ' by dropping all tables ';            Dropalltables (db, true);        OnCreate (DB); }} public Daomaster (SQLiTedatabase db) {super (db, schema_version);    Registerdaoclass (Userdao.class);    } public daosession NewSession () {return new daosession (db, Identityscopetype.session, daoconfigmap);    } public daosession NewSession (identityscopetype type) {return new daosession (db, type, daoconfigmap); }}

The ultimate goal of Dbmaster is to obtain DbSession , by DbSession manipulating the database.

Next article said Greendao specific use, please look forward to ~

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Android] Greendao (1)--project configuration

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.