GreenDao数据库的使用方法

Project gradle依赖

buildscript {
    repositories {
        jcenter()

        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.1'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'

Module gradle依赖
apply plugin: 'org.greenrobot.greendao'
compile 'org.greenrobot:greendao:3.2.2'
greendao {
    schemaVersion 1
    daoPackage 'com.example.zhang20171130.gen'   //改成当前工程的包名.gen
    targetGenDir 'src/main/java' }
 
  
在Bean类中加入注解
@Entity
public class Person {
    @Id
    private Long id;
 
  
Build--Make Module 编译一下
 
  
DbHelper
public class DbHelper {
    private static volatile DbHelper instance;
    private final DaoSession daoSession;
    private final DaoMaster daoMaster;


    public DbHelper(Context context) {
        //初始化数据库的一些配置
        DaoMaster.DevOpenHelper helper=new DaoMaster.DevOpenHelper(context,"user",null);
        //获取数据库的操作对象
        SQLiteDatabase database = helper.getWritableDatabase();
        //获取DaoMaster对象
        daoMaster = new DaoMaster(database);
        //获取DaoSession对象
        daoSession =daoMaster.newSession();

    }
    public static DbHelper getInstance(Context context){
        if(instance == null){
            synchronized (DbHelper.class){
                if(null==instance){
                    instance=new DbHelper(context);
                }

            }
        }
        return instance;
    }
    public PersonDao getPerson(){
        return daoSession.getPersonDao();
    }

}
增删改查的方法
 
  
 
  
@OnClick({R.id.zeng, R.id.shan, R.id.gai, R.id.cha})
public void onViewClicked(View view) {
    switch (view.getId()) {
        case R.id.zeng:
            Person p=new Person();
            p.setId(Long.parseLong(ed1.getText().toString()));
            p.setName(ed2.getText().toString());
            dao.insert(p);
            break;
        case R.id.shan:
            Person p1=new Person();
            p1.setId(Long.parseLong(ed1.getText().toString()));
            p1.setName(ed2.getText().toString());
            dao.delete(p1);
            break;
        case R.id.gai:
            Person p2=new Person(Long.parseLong(ed1.getText().toString()),ed2.getText().toString());
            dao.update(p2);
            break;
        case R.id.cha:
            persons = dao.loadAll();
            adapter = new Adapter(this,persons);
            lv.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            break;
    }
}
 
  

你可能感兴趣的:(GreenDao数据库的使用方法)