Android GreenDao3.2.0教程(附Demo)

1.先上测试界面截图

Android GreenDao3.2.0教程(附Demo)_第1张图片
image.png

懒得写布局的话,可以直接复制粘贴




    
    
    
    

2.实体类
一个实体类,对应一张表单

@Entity
public class WorkLogBean {
    @Id(autoincrement = true)
    @Unique
    private Long id;      //主键自增长,不可重复,作为不同记录对象的标识,传入参数对象时不要传入

    //时间戳
    @Property(nameInDb = "TIMELONG")
    private Long timeLong;

    //时间对应格式字符串
    @Property(nameInDb = "TIMESTR")
    private String timeStr;

    //内容描述
    @Property(nameInDb = "DESCRIPTION")
    private String description;
}

然后点击Android Studio


image.png

小锤子,之后 bean类会变成这样

package com.zzb.greendaodemo.db;

import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Property;
import org.greenrobot.greendao.annotation.Unique;
import org.greenrobot.greendao.annotation.Generated;

/**
* Created by ZZB on 2017/6/28.
*/

@Entity
public class WorkLogBean {
    @Id(autoincrement = true)
    @Unique
    private Long id;      //主键自增长,不可重复,作为不同记录对象的标识,传入参数对象时不要传入

    //时间戳
    @Property(nameInDb = "TIMELONG")
    private Long timeLong;

    //时间对应格式字符串
    @Property(nameInDb = "TIMESTR")
    private String timeStr;

    //内容描述
    @Property(nameInDb = "DESCRIPTION")
    private String description;

    @Generated(hash = 5215746)
    public WorkLogBean(Long id, Long timeLong, String timeStr, String description) {
        this.id = id;
        this.timeLong = timeLong;
        this.timeStr = timeStr;
        this.description = description;
    }

    @Generated(hash = 1301884914)
    public WorkLogBean() {
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getTimeLong() {
        return this.timeLong;
    }

    public void setTimeLong(Long timeLong) {
        this.timeLong = timeLong;
    }

    public String getTimeStr() {
        return this.timeStr;
    }

    public void setTimeStr(String timeStr) {
        this.timeStr = timeStr;
    }

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
     
    @Override
    public String toString() {
        return "WorkLogBean{" +
                "id=" + id +
                ", timeLong=" + timeLong +
                ", timeStr='" + timeStr + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
}

以及会自动生成其余类

Android GreenDao3.2.0教程(附Demo)_第2张图片
image.png

DaoMaster、DaoSession、WorkLogBeanDao都是自动生成的

现在开始假如我们的需求是这样的:
①点击按钮可以从数据库中获取到全部的内容
②全部内容都展示在listView上,然后点击条目的时候,删除这个条目
③一直需要判断现实中时间,数据库中是否保存了时间,保存了时间,就需要处理一些逻辑。。

根据上面的需求,接下来新建一个类DbUtils,开始封装我们的工具类:

Android GreenDao3.2.0教程(附Demo)_第3张图片
image.png
package com.zzb.greendaodemo.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.zzb.greendaodemo.BaseApplication;

import org.greenrobot.greendao.query.DeleteQuery;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

/**
* Created by ZZB on 2017/6/28.
*/

public class DbUtils {
    private static DbUtils dbUtils;
    /**数据库名称*/
    private final static String dbName = "worklog.db";
    private DaoMaster.DevOpenHelper openHelper;
    private Context context;

    private DbUtils() {
        context = BaseApplication.mContext;
        openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
    }

    /**
    * 获取单例
    *
    * @return
    */
    public static DbUtils getInstance() {
        if (dbUtils == null) {
            synchronized (DbUtils.class) {
                if (dbUtils == null) {
                    dbUtils = new DbUtils();
                }
            }
        }
        return dbUtils;
    }

    /**
    * 获取可读数据库
    */
    private SQLiteDatabase getReadableDatabase() {
        if (openHelper == null) {
            openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
        }
        SQLiteDatabase db = openHelper.getReadableDatabase();
        return db;
    }

    /**
    * 获取可写数据库
    */
    private SQLiteDatabase getWritableDatabase() {
        if (openHelper == null) {
            openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
        }
        SQLiteDatabase db = openHelper.getWritableDatabase();
        return db;
    }

    /**
    * 保存或替换
    * @param bean
    */
    public void saveData(WorkLogBean bean) {
        DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        WorkLogBeanDao chatListDao = daoSession.getWorkLogBeanDao();
        chatListDao.insertOrReplace(bean);
    }

    /**
    * 通过时间查找所有列表,按时间倒序
    */
    public List queryAllData() {
        try {
            DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
            DaoSession daoSession = daoMaster.newSession();
            WorkLogBeanDao chatListDao = daoSession.getWorkLogBeanDao();
            QueryBuilder qb = chatListDao.queryBuilder();
            qb.orderDesc(WorkLogBeanDao.Properties.TimeLong);
            List chatLists = qb.list();
            return chatLists;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
    * 分页查询,每页10条数据,按时间降序
    * @param page  查询的页数,从0开始
    * @return
    */
    public List queryPageLists(int page) {
        try {
            DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
            DaoSession daoSession = daoMaster.newSession();
            WorkLogBeanDao chatListDao = daoSession.getWorkLogBeanDao();
            QueryBuilder qb = chatListDao.queryBuilder();
            qb.orderDesc(WorkLogBeanDao.Properties.TimeLong).offset(page * 10).limit(10);;
            List chatLists = qb.list();
            return chatLists;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
    * 获取此时间对应的对象
    * @return
    */
    public List queryDataFromTime(String timeStr) {
        try {
            DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
            DaoSession daoSession = daoMaster.newSession();
            WorkLogBeanDao chatListDao = daoSession.getWorkLogBeanDao();
            QueryBuilder qb = chatListDao.queryBuilder();
            qb.where(WorkLogBeanDao.Properties.TimeStr.eq(timeStr));
            List chatLists = qb.list();
            return chatLists;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
    * 将此时间的数据删除
    * @param timeStr
    */
    public void deleteDataFromTime(String timeStr) {
        try {
            DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
            DaoSession daoSession = daoMaster.newSession();
            WorkLogBeanDao chatListDao = daoSession.getWorkLogBeanDao();
            QueryBuilder qb = chatListDao.queryBuilder();
            DeleteQuery bd = qb.where(WorkLogBeanDao.Properties.TimeStr.eq(timeStr)).buildDelete();
            bd.executeDeleteWithoutDetachingEntities();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

好了,下面可以直接使用了,在我们的MainActivity中:

package com.zzb.greendaodemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.zzb.greendaodemo.db.DbUtils;
import com.zzb.greendaodemo.db.WorkLogBean;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.et_time)
    EditText etTime;
    @BindView(R.id.et_description)
    EditText etDescription;
    @BindView(R.id.et_query_time)
    EditText etQueryTime;
    @BindView(R.id.tv_show_content)
    TextView tvShowContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_save, R.id.btn_get, R.id.btn_get_all})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_save: //保存数据
                String time = etTime.getText().toString().trim();
                long timeLong = parseStrToLong(time);
                String description = etDescription.getText().toString().trim();
                WorkLogBean workLogBean = new WorkLogBean();
                workLogBean.setTimeStr(time);
                workLogBean.setTimeLong(timeLong);
                workLogBean.setDescription(description);
                DbUtils.getInstance().saveData(workLogBean);
                break;
            case R.id.btn_get: //查询指定时间数据
                String quertTime = etQueryTime.getText().toString().toString();
                List datas = DbUtils.getInstance().queryDataFromTime(quertTime);
                tvShowContent.setText(datas == null ? "查询数据为空" : datas.toString());
                break;
            case R.id.btn_get_all: //查询所有数据
                List list = DbUtils.getInstance().queryAllData();
                tvShowContent.setText(list == null ? "查询数据为空" : list.toString() );
                break;
        }
    }

    /**
    * @param timeStr
    * @return
    */
    private long parseStrToLong(String timeStr) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return simpleDateFormat.parse(timeStr).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }

    private String parseLongToStr(Long timeLong) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return simpleDateFormat.format(new Date(timeLong));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

所有的操作已经完成了,我们可以直接运行看效果了:
点击保存数据之后,又点击获取当前时间后的效果

Android GreenDao3.2.0教程(附Demo)_第4张图片
image.png

点击获取所有数据的效果:

Android GreenDao3.2.0教程(附Demo)_第5张图片
image.png

如果想深入的学习、应用,可以看我的另一篇文章,在真实项目中的实际应用:
http://www.jianshu.com/p/b1b2d3333fca
并附上Demo下载链接:
https://github.com/xiaozhu1989/greenDaoDemo/

你可能感兴趣的:(Android GreenDao3.2.0教程(附Demo))