使用GreenDao创建数据库

一.创建一个自定义Application类

//MyApplication在应用开启的同时第一个被执行(必须把Application类添加到清单文件中)
public class MyApplication extends Application{

    private DaoMaster daoMaster;
    private static DaoSession daoSession;
    @Override
    public void onCreate() {
        super.onCreate();
        OkHttpClient okHttpClient=new OkHttpClient.Builder()
                .connectTimeout(3000, TimeUnit.SECONDS)
                .writeTimeout(3000,TimeUnit.SECONDS)
                .build();
        OkHttpUtils.initClient(okHttpClient);

        //初始化GreenDao
        //创建数据库,参数1:上下文,参数2:库名,参数3:游标工厂
        DaoMaster.DevOpenHelper devOpenHelper=new DaoMaster.DevOpenHelper(getApplicationContext(),"zhiyuan.db",null);
        //实例化DaoMaster对象
        daoMaster=new DaoMaster(devOpenHelper.getWritableDb());
        //实例化DaoSession对象
        daoSession=daoMaster.newSession();

    }
    //以后每次实现增删改查,都要通过此方法
    public static DaoSession getDaoSession(){
        return daoSession;
    }
}
二.把自定义Application类添加到清单文件中
   
  
  
三.创建一个User类,封装一些数据
@Entity(nameInDb = "users")
public class User {
    @Id(autoincrement = true)
    private Long id;
    @Property(nameInDb = "users_name")
    private String name;
    @Property(nameInDb = "users_pass")
    private String pass;
}
四.点击工具栏的锤子按钮进行编译(会运行一下程序但不会启动虚拟机)
编译完之后系统会给User类中自动添加set和get方法,并且在同一个包下自动创建
3个类DaoMaster,DaoSession,UserDao
@Entity(nameInDb = "users")
public class User {
    @Id(autoincrement = true)
    private Long id;
    @Property(nameInDb = "users_name")
    private String name;
    @Property(nameInDb = "users_pass")
    private String pass;
    @Generated(hash = 1501192064)
    public User(Long id, String name, String pass) {
        this.id = id;
        this.name = name;
        this.pass = pass;
    }
    @Generated(hash = 586692638)
    public User() {
    }
    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPass() {
        return this.pass;
    }
    public void setPass(String pass) {
        this.pass = pass;
    }
}
五.在其他类中进行增删改查操作
public class SocietyFragment extends Fragment{
    @BindView(R.id.button2)
    Button btn;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.shehui_fragment,container,false);
        ButterKnife.bind(this,view);
        btn.setText("插入");
        return view;
    }
    @OnClick(R.id.button2)
    public void run(){
        User user=new User(null,"鸣人","123456");
        //通过session获取想要插入的表单的Dao类,然后调用insert方法,插人User对象
        MyApplication.getDaoSession().getUserDao().insert(user);
        Toast.makeText(getContext(),"插入成功",Toast.LENGTH_LONG).show();
    }
}






你可能感兴趣的:(学习交流,greenDao)