Android——Greendao封装进行

 

关于GreenDao

 

greenDao是一个将对象映射到SQLite数据库中的轻量且快速的ORM解决方案。
关于greenDAO的概念可以看官网greenDAO

 

greenDAO 优势

 

1、一个精简的库
2、性能最大化
3、内存开销最小化
4、易于使用的 APIs
5、对 Android 进行高度优化

 

GreenDao 3.0使用

GreenDao 3.0采用注解的方式来定义实体类,通过gradle插件生成相应的代码。

 

 

第一步 在工程的Build Gridle中进行配置

 

dependencies {
    classpath 'com.android.tools.build:gradle:2.3.3'
    classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'//加入
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

第二步 在Demo的Build Gridle中配置

 

 

apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'//加入
android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"

    defaultConfig {
        applicationId "com.bwie.com.myapplication"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

添加依赖

 

 

compile 'org.greenrobot:greendao:3.2.2'

第三步 自定义路径

 

 

greendao {
    schemaVersion 1
    daoPackage 'com.bwie.com.myapplication.gen'
    targetGenDir 'src/main/java'
}

 

第四步 创建一个实体类

 

@Entity
public class DataBean {
    @Id
    private long cid;
    private String createtime;
    private String icon;
    private int ishome;
    private String name;
}

第五步 MakeProject 自动编译 会在gen目录下生成三个文件

 

Android——Greendao封装进行_第1张图片Android——Greendao封装进行_第2张图片

 

下面上代码:

先进行网络请求:

HttpUtils/**
* Created by Wangrx on 2017/11/30.
*/

public class HttpUtils {
private static volatile HttpUtils instance;
private Handler handler = new Handler();
private HttpUtils(){

}
public static HttpUtils getInstance(){
if (instance==null){
synchronized (HttpUtils.class){
if (null==instance){
instance = new HttpUtils();
}
}
}
return instance;
}
public void get(String url, Map map, final CallBack callBack, final Class cls, final String tag){
if (TextUtils.isEmpty(url)){
return;
}
StringBuffer sb = new StringBuffer();
sb.append(url);
if (url.contains("?")){
if (url.indexOf("?")==url.length()-1){

}else {
sb.append("&");
}
}else {
sb.append("?");
}
for (Map.Entry entry:map.entrySet()){
sb.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append("&");
}
if (sb.indexOf("&")!=-1){
sb.deleteCharAt(sb.lastIndexOf("&"));
}
OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
.get()
.url(sb.toString())
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
callBack.onFailed(tag,e);
}
});
}

@Override
public void onResponse(Call call, Response response) throws IOException {
final String result = response.body().string();
//请求成功后做解析,通过自己的回调接口将数据返回去
handler.post(new Runnable() {
@Override
public void run() {
Object o;
if (TextUtils.isEmpty(result)){
o = null;
}else {
o = GsonUtils.getInstance().fromJson(result, cls);
}
callBack.onSuccess(tag,o);
}
});
}
});
}
}

/**
* Created by Wangrx on 2017/11/30.
*/

public class GsonUtils {
private static Gson instance;
private GsonUtils(){

}
public static Gson getInstance(){
if (instance==null){
instance = new Gson();
}
return instance;
}
}

GsonUtils/**
* Created by Wangrx on 2017/11/30.
*/

public class GsonUtils {
private static Gson instance;
private GsonUtils(){

}
public static Gson getInstance(){
if (instance==null){
instance = new Gson();
}
return instance;
}
}

CallBack/**
* Created by Wangrx on 2017/11/30.
*/

public interface CallBack {
void onSuccess(String tag,Object o);
void onFailed(String tag,Exception e);
}

NewsPresenter/**
* Created by Wangrx on 2017/11/30.
*/

public class NewsPresenter {
private NewsView inv;
public void attachView(NewsView inv){
this.inv = inv;
}
public void getNews(String url){
Map map = new HashMap<>();
// map.put("keywords",show);
// map.put("page",page+"");
HttpUtils.getInstance().get(url, map, new CallBack() {
@Override
public void onSuccess(String tag, Object o) {
JavaBean bean = (JavaBean) o;
if (bean != null){
List data = bean.getData();
inv.success(tag,data);

}
}

@Override
public void onFailed(String tag, Exception e) {
inv.failed(tag,e);
}
}, JavaBean.class,"news");
}
public void detachView(){
if (inv!=null){
inv = null;
}
}
}

NewsView/**
* Created by Wangrx on 2017/11/30.
*/

public interface NewsView {
void success(String tag, List data);
void failed(String tag,Exception e);
}

 

以上是对网络请求数据以MVP模式进行封装

下面是对GreenDao的封装

BaseApplication(本地的数据)/**
* Created by Wangrx on 2017/11/30.
*/

public class BaseApplication extends Application{
private static BaseApplication instance;
private List list;
@Override
public void onCreate() {
super.onCreate();
instance=this;
}
public static BaseApplication getInstance(){
return instance;
}
public List getData(){
if (list==null){
list=new ArrayList<>();
}
return list;
}
public void setData(List list){
this.list = list;
}
}

DBUtils(数据库中的数据)/**
* Created by Wangrx on 2017/11/30.
*/

public class DBUtils {
private static volatile DBUtils instance;
private final DataBeanDao dao;

public DBUtils(Context context) {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "databean.db", null);
SQLiteDatabase database = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(database);
DaoSession daoSession = daoMaster.newSession();
dao = daoSession.getDataBeanDao();

}
public static DBUtils getInstance(Context context){
if (instance==null){
synchronized (DBUtils.class){
if (null==instance){
instance = new DBUtils(context);
}
}
}
return instance;
}
public DataBeanDao getDao(){
return dao;
}
}

MainActivity(先判断本地是否有数据,没有的话从数据库中取出数据,判断数据库是否有数据,数据库中有数据的话将数据查询出来赋给本地数据,数据库中也没有数据的话就从网络上获取数据,网络上获取到数据后将数据存入数据库中,同时也赋给本地数据,将本地的数据拿出显示出来public class MainActivity extends AppCompatActivity implements NewsView {

@BindView(R.id.recy_vieww)
RecyclerView recyVieww;
private List datas;
private MyAdapter adapter;
private NewsPresenter presenter;
private DataBeanDao dao;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
dao = DBUtils.getInstance(this).getDao();
initView();


}

public void initView() {

//首先从内存中看有没有数据
datas = BaseApplication.getInstance().getData();
adapter = new MyAdapter(this, datas);
LinearLayoutManager manager = new LinearLayoutManager(this);
recyVieww.setLayoutManager(manager);


recyVieww.setAdapter(adapter);
if (datas == null || datas.size() == 0) {
Log.i("zzz", "内存中无数据");
//从数据库中取
List dataFromDB = getDataFromDB();
//数据库中也是空
if (dataFromDB==null||dataFromDB.size()==0){
Log.i("zzz", "数据控中为空");
//从网络中取数据
getDataFromNet();
}else {
Log.i("zzz", "数据库中不为空");
putDataToMemory(dataFromDB);
}
}
adapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
@Override
public void onClick(int position) {
// DataBean dataBean = new DataBean();
// dataBean.setCid(position+1);
// dao.delete(dataBean);
// List dataFromDB = getDataFromDB();
// putDataToMemory(dataFromDB);
}

@Override
public void onLongClick(int position) {

}
});


}

//从网络中取数据
public void getDataFromNet(){
Log.i("zzz", "从网上获取");
presenter = new NewsPresenter();
presenter.attachView(this);
presenter.getNews("https://www.zhaoapi.cn/product/getCatagory");

}


@Override
public void success(String tag, List data) {
if (data!=null){
Log.i("zzz", "网络不为空");
//将网络请求的数据存到内存中和数据库中
putDataToMemory(data);
//将数据添加到数据库中
for (DataBean dataBean : data){
dao.insertOrReplace(dataBean);
}

}

}
//将数据添加到内存中
public void putDataToMemory(List data){
Log.i("zzz", "向内存中存数据");
datas.clear();
datas.addAll(data);
adapter.notifyDataSetChanged();
BaseApplication.getInstance().setData(datas);
}
//从数据库中取数据
public List getDataFromDB(){
Log.i("zzz", "从数据库中取");
//查询所有数据
List dataBeen = dao.loadAll();
if (dataBeen==null||dataBeen.size()==0){
Log.i("zzz", "null");
}else {
Log.i("zzz", "getDataFromDB: "+dataBeen.size());
}
return dataBeen;
}
@Override
public void failed(String tag, Exception e) {

}

@Override
protected void onDestroy() {
super.onDestroy();
if (presenter != null) {
presenter.detachView();
}
}
}

MyAdapter/**
* Created by Wangrx on 2017/11/30.
*/

public class MyAdapter extends RecyclerView.Adapter {


private Context context;
private List list;

public MyAdapter(Context context, List list) {
this.context = context;
this.list = list;
}

private OnItemClickListener mOnItemClickListener;

public interface OnItemClickListener{
void onClick( int position);
void onLongClick( int position);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener ){
this. mOnItemClickListener=onItemClickListener;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(context, R.layout.item, null);
ViewHolder holder = new ViewHolder(view);
return holder;
}

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.itemTitle.setText(list.get(position).getName());
holder.itemTime.setText(list.get(position).getCreatetime());
if( mOnItemClickListener!= null){
holder.itemView.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
mOnItemClickListener.onClick(position);
}
});
holder. itemView.setOnLongClickListener( new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
mOnItemClickListener.onLongClick(position);
return false;
}
});
}
}

@Override
public int getItemCount() {
return list.size();
}


public class ViewHolder extends RecyclerView.ViewHolder {

@BindView(R.id.item_title)
TextView itemTitle;
@BindView(R.id.item_time)
TextView itemTime;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);
}
}
}

 

 

 

你可能感兴趣的:(移动开发)