1.先上測(cè)試界面截圖
懶得寫布局的話闲勺,可以直接復(fù)制粘貼
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.zzb.greendaodemo.MainActivity">
<EditText
android:id="@+id/et_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請(qǐng)輸入保存時(shí)間"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="時(shí)間格式輸入例如: 2017-10-18 19:30"/>
<EditText
android:id="@+id/et_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請(qǐng)輸入保存內(nèi)容"
/>
<Button
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="保存數(shù)據(jù)"/>
<EditText
android:id="@+id/et_query_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="請(qǐng)輸入查詢時(shí)間"
/>
<Button
android:id="@+id/btn_get"
android:text="獲取當(dāng)前時(shí)間數(shù)據(jù)"
android:layout_width="match_parent"
android:layout_height="60dp"/>
<Button
android:id="@+id/btn_get_all"
android:text="獲取所有數(shù)據(jù)"
android:layout_width="match_parent"
android:layout_height="60dp"/>
<TextView
android:id="@+id/tv_show_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
2.實(shí)體類
一個(gè)實(shí)體類绿贞,對(duì)應(yīng)一張表單
@Entity
public class WorkLogBean {
@Id(autoincrement = true)
@Unique
private Long id; //主鍵自增長(zhǎng)陋守,不可重復(fù),作為不同記錄對(duì)象的標(biāo)識(shí),傳入?yún)?shù)對(duì)象時(shí)不要傳入
//時(shí)間戳
@Property(nameInDb = "TIMELONG")
private Long timeLong;
//時(shí)間對(duì)應(yīng)格式字符串
@Property(nameInDb = "TIMESTR")
private String timeStr;
//內(nèi)容描述
@Property(nameInDb = "DESCRIPTION")
private String description;
}
然后點(diǎn)擊Android Studio
小錘子淹魄,之后 bean類會(huì)變成這樣
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; //主鍵自增長(zhǎng)郁惜,不可重復(fù),作為不同記錄對(duì)象的標(biāo)識(shí),傳入?yún)?shù)對(duì)象時(shí)不要傳入
//時(shí)間戳
@Property(nameInDb = "TIMELONG")
private Long timeLong;
//時(shí)間對(duì)應(yīng)格式字符串
@Property(nameInDb = "TIMESTR")
private String timeStr;
//內(nèi)容描述
@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 + '\'' +
'}';
}
}
以及會(huì)自動(dòng)生成其余類
DaoMaster甲锡、DaoSession兆蕉、WorkLogBeanDao都是自動(dòng)生成的
現(xiàn)在開始假如我們的需求是這樣的:
①點(diǎn)擊按鈕可以從數(shù)據(jù)庫(kù)中獲取到全部的內(nèi)容
②全部?jī)?nèi)容都展示在listView上羽戒,然后點(diǎn)擊條目的時(shí)候,刪除這個(gè)條目
③一直需要判斷現(xiàn)實(shí)中時(shí)間虎韵,數(shù)據(jù)庫(kù)中是否保存了時(shí)間易稠,保存了時(shí)間,就需要處理一些邏輯包蓝。驶社。
根據(jù)上面的需求,接下來(lái)新建一個(gè)類DbUtils测萎,開始封裝我們的工具類:
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;
/**數(shù)據(jù)庫(kù)名稱*/
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;
}
/**
* 獲取可讀數(shù)據(jù)庫(kù)
*/
private SQLiteDatabase getReadableDatabase() {
if (openHelper == null) {
openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}
SQLiteDatabase db = openHelper.getReadableDatabase();
return db;
}
/**
* 獲取可寫數(shù)據(jù)庫(kù)
*/
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);
}
/**
* 通過(guò)時(shí)間查找所有列表亡电,按時(shí)間倒序
*/
public List<WorkLogBean> queryAllData() {
try {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
WorkLogBeanDao chatListDao = daoSession.getWorkLogBeanDao();
QueryBuilder<WorkLogBean> qb = chatListDao.queryBuilder();
qb.orderDesc(WorkLogBeanDao.Properties.TimeLong);
List<WorkLogBean> chatLists = qb.list();
return chatLists;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 分頁(yè)查詢,每頁(yè)10條數(shù)據(jù),按時(shí)間降序
* @param page 查詢的頁(yè)數(shù),從0開始
* @return
*/
public List<WorkLogBean> queryPageLists(int page) {
try {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
WorkLogBeanDao chatListDao = daoSession.getWorkLogBeanDao();
QueryBuilder<WorkLogBean> qb = chatListDao.queryBuilder();
qb.orderDesc(WorkLogBeanDao.Properties.TimeLong).offset(page * 10).limit(10);;
List<WorkLogBean> chatLists = qb.list();
return chatLists;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 獲取此時(shí)間對(duì)應(yīng)的對(duì)象
* @return
*/
public List<WorkLogBean> queryDataFromTime(String timeStr) {
try {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
WorkLogBeanDao chatListDao = daoSession.getWorkLogBeanDao();
QueryBuilder<WorkLogBean> qb = chatListDao.queryBuilder();
qb.where(WorkLogBeanDao.Properties.TimeStr.eq(timeStr));
List<WorkLogBean> chatLists = qb.list();
return chatLists;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 將此時(shí)間的數(shù)據(jù)刪除
* @param timeStr
*/
public void deleteDataFromTime(String timeStr) {
try {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
WorkLogBeanDao chatListDao = daoSession.getWorkLogBeanDao();
QueryBuilder<WorkLogBean> qb = chatListDao.queryBuilder();
DeleteQuery<WorkLogBean> 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: //保存數(shù)據(jù)
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: //查詢指定時(shí)間數(shù)據(jù)
String quertTime = etQueryTime.getText().toString().toString();
List<WorkLogBean> datas = DbUtils.getInstance().queryDataFromTime(quertTime);
tvShowContent.setText(datas == null ? "查詢數(shù)據(jù)為空" : datas.toString());
break;
case R.id.btn_get_all: //查詢所有數(shù)據(jù)
List<WorkLogBean> list = DbUtils.getInstance().queryAllData();
tvShowContent.setText(list == null ? "查詢數(shù)據(jù)為空" : 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;
}
}
所有的操作已經(jīng)完成了,我們可以直接運(yùn)行看效果了:
點(diǎn)擊保存數(shù)據(jù)之后零酪,又點(diǎn)擊獲取當(dāng)前時(shí)間后的效果
點(diǎn)擊獲取所有數(shù)據(jù)的效果:
如果想深入的學(xué)習(xí)、應(yīng)用拇勃,可以看我的另一篇文章四苇,在真實(shí)項(xiàng)目中的實(shí)際應(yīng)用:
http://www.reibang.com/p/b1b2d3333fca
并附上Demo下載鏈接:
https://github.com/xiaozhu1989/greenDaoDemo/