android studio 引入greendao

来源:互联网 发布:周杰伦中文网淘宝店 编辑:程序博客网 时间:2024/04/27 17:37

greendao 3.0的引入变得有点复杂了,但是使用起来却是更加方便了,但是从网上搜索了一下还是很多小伙伴

想引入greendao,但是不知道如何引入,面对github 给的源码头大如斗,下面就是一些简单的配置



1.由于greendao在3.0中加入了注入编译工具  必须在根目录的 build.gradle 文件中插入
dependencies {
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'
    }
######编译app############




2.引用greendao  在主项目 build.gradle  文件中插入
dependencies {
    compile 'org.greenrobot:greendao:3.2.0'
}
######编译app############




3.这个时候看代码     发现App这个类中引入了 DaoSession 这个类,但是代码copy过来却说无法找到这个类,
注释掉这些代码,此类必须经过特殊编译才会生成
  
  在主项目中有一个Note的Bean,  DaoSession这个类就是通过第1步中的工具生成的,而你仅仅只要写几行代码
  
  @Entity   /////必须标注    注明该实体类为  greendao  需要编译的实体
  public class Note{
@id  /////必须标注   注明_id  且id 必须为long类型,  
private Long id;

@NotNull////非空
    private String text;

    private String comment;
    private Java.util.Date date;
  }
  其中必须存在的注入属性 @Entity 和 @id 必须存在,
  如果只有一个属性的 Note bean 看不出来green有多少的神奇,我又加了几个别的
  而且你只需要添加属性即可,剩下的工作greendao 的工具都会帮你自动添加 
  ######编译app############
  
  
4.由于没有配置  greendao 的编译路径,所以目前编译后的目录都在引用第2步中引用该项目的 build(编译目录) 
build\generated\source\greendao  目录下
  
5. 现在这个时候就可以简单的使用greendao了,将App类中的代码copy过来,Activity中的代码稍微修改一些就可以了,


总结:虽然现在使用greendao的引入步骤麻烦了很多,但是通过配置却让他的使用方法简化的太多了,




public class App extends Application {
    public static final boolean ENCRYPTED = false;
    private DaoSession daoSession;
    @Override
    public void onCreate() {
        super.onCreate();
        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 DaoSession getDaoSession(){
        return  daoSession;
    }
}




public class MainActivity extends Activity {
    private TestModel test;
    private NoteDao dao;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DaoSession daoSession = ((App) this.getApplication()).getDaoSession();
        dao = daoSession.getNoteDao();
        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                insert();
            }
        });
    }
    private void insert(){
        Note note=new Note(null,""+new Random().nextInt(),"",new Date(System.currentTimeMillis()));
        dao.insert(note);
        List<Note> list = dao.loadAll();
        for (int i=0;i<list.size();i++){
            Log.i("info"," Note"+i+"--->"+list.get(i).toString());
        }
    }
}


demo中的混淆应该是可以用的   直接 debug 就是为项目自动签名打包

demo的下载路径,

http://download.csdn.NET/detail/qq_22256027/9662106

0 0