Android_简单三级缓存 (数据库)

//GreenDao的依赖

// In your root build.gradle file:
buildscript {
    repositories {
        jcenter()
        mavenCentral() // add repository
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
    }
}
 
// In your app projects build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin
 
dependencies {
    compile 'org.greenrobot:greendao:3.2.2' // add library
}
demo

greendao {
    schemaVersion 1
    daoPackage 'com.bwei.www.greendao.gen'
    targetGenDir 'src/main/java'
}
//布局:

MainActivity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/lv_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></ListView>

</LinearLayout>
item_data:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txt_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/txt_time"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
//bean类:

MessageBean:

package com.bwei.www.sanjinhuan.bean;

import java.util.List;

public class MessageBean {
    private String msg;
    private String code;
    private List<Category> data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public List<Category> getData() {
        return data;
    }

    public void setData(List<Category> data) {
        this.data = data;
    }
}
CateGory:

package com.bwei.www.sanjinhuan.bean;

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


@Entity
public class Category {
    @Id
    private Long cid;
    private String createtime;
    private String icon;
    private int ishome;
    private String name;
    @Generated(hash = 1052838896)
    public Category(Long cid, String createtime, String icon, int ishome,
            String name) {
        this.cid = cid;
        this.createtime = createtime;
        this.icon = icon;
        this.ishome = ishome;
        this.name = name;
    }
    @Generated(hash = 1150634039)
    public Category() {
    }
    public Long getCid() {
        return this.cid;
    }
    public void setCid(Long cid) {
        this.cid = cid;
    }
    public String getCreatetime() {
        return this.createtime;
    }
    public void setCreatetime(String createtime) {
        this.createtime = createtime;
    }
    public String getIcon() {
        return this.icon;
    }
    public void setIcon(String icon) {
        this.icon = icon;
    }
    public int getIshome() {
        return this.ishome;
    }
    public void setIshome(int ishome) {
        this.ishome = ishome;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
// BaseApplication:

这里一定必要忘了在清单文件注册

public class BaseApplication extends Application {
    private static  BaseApplication instance;
    private List<Category> list;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static BaseApplication getInstance(){
        return instance;
    }

    public List<Category> getdata() {
        if(list==null){
            list = new ArrayList<>();
        }
        return list;
    }
    public void setdata(List<Category> list){
        this.list = list;
    }
}



//封装数据库工具类 DBUtils
public class DBUtils {
    private static  volatile DBUtils instance;
    private final CategoryDao dao;

    public DBUtils(Context context){
        final DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "user.db", null);
        final SQLiteDatabase database = helper.getWritableDatabase();
        final DaoMaster daoMaster = new DaoMaster(database);
        final DaoSession daoSession = daoMaster.newSession();
        dao = daoSession.getCategoryDao();
    }
    public static DBUtils getInstance(Context context){
        if(instance==null){
            synchronized (DBUtils.class){
                if(null==instance){
                    instance = new DBUtils(context);
                }
            }
        }
        return instance;
    }

    public CategoryDao getDao(){
        return dao;
    }
}
//接口
public interface CallBack {
    void onSuccess(Object o);

    void onFailed(Exception e);
}


//封装网络请求工具类
public class HttpUtils {
    public static volatile HttpUtils instance;
    public Handler handler = new Handler();
    public static HttpUtils getInstance() {
        if (instance == null) {
            synchronized (HttpUtils.class) {
                if (null == instance) {
                    instance = new HttpUtils();
                }
            }
        }
        return instance;
    }
    public void get(String url, final CallBack callBack, final Class cls){
        final OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        final 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(e);
                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                Log.e("4567896543", "onResponse: "+result );
                final Gson gson = new Gson();
                final Object o = gson.fromJson(result, cls);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onSuccess(o);
                    }
                });
            }
        });
    }

}
//MainActivity:
public class MainActivity extends AppCompatActivity {

    @BindView(R.id.lv_data)
    ListView lvData;
    private List<Category> getdata;
    private CategoryDao dao;
    private DataAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        dao = DBUtils.getInstance(this).getDao();
        //首先从内存中看有没有数据
        getdata = BaseApplication.getInstance().getdata();
        adapter = new DataAdapter(this, getdata);
        lvData.setAdapter(adapter);
        if(getdata==null || getdata.size()==0){
            Log.e("-=-=-", "onCreate: "+"内存中无数据" );
           //从数据库中取
            final List<Category> list = getDataFromDb();
            if(list==null||list.size()==0){
                //从网络加载
                Log.e("----", "onCreate: "+"从网络加载" );
                getDataFromNet();
            }
        }
    }
    //从网络请求
    public void getDataFromNet(){
        Log.e("=====", "getDataFromNet: "+"从网络请求" );
        HttpUtils.getInstance().get("https://www.zhaoapi.cn/product/getCatagory", new CallBack() {
            @Override
            public void onSuccess(Object o) {
                MessageBean bean = (MessageBean) o;
                Log.e("00000000", "onSuccess: "+bean.getMsg() );
                if (bean != null) {
                    List<Category> data = bean.getData();
                    if (data != null) {
                        Log.i("oooo", "onSuccess: 网络不为空");
                        // 将网络请求的数据存到内存和数据库中
                        putDataToMemory(data);
                        // 蒋数据添加到数据库中
                        for (Category category : data) {

                            dao.insertOrReplace(category);

                        }

                    }
                }
            }


            @Override
            public void onFailed(Exception e) {
                Log.e("[][][]", "onFailed: "+e.getMessage() );
            }
        }, MessageBean.class);
    }
    //将数据添加到内存中
    private void putDataToMemory(List<Category> data) {
        Log.e("99999", "putDataToMemory: "+"向内存中存数据" );
        getdata.clear();
        getdata.addAll(data);
        adapter.notifyDataSetChanged();
        BaseApplication.getInstance().setdata(getdata);
    }

    //从数据获取
    public List<Category> getDataFromDb(){
        Log.e("1111", "getDataFromDb: "+"从数据库取" );
        final List<Category> categories = dao.loadAll();
        if(categories==null || categories.size()==0){
            Log.e("qqq", "getDataFromDb: "+null );
        }else{
            Log.e("www", "getDataFromDb: "+categories.size() );
        }
        return categories;
    }

}
//适配器:
public class DataAdapter extends BaseAdapter {
    private Context context;
    private List<Category> list;

    public DataAdapter(Context context, List<Category> list) {
        this.context = context;
        this.list = list;
    }

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

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder = null;
        if (view == null) {
            view = View.inflate(context, R.layout.item_data, null);
            holder = new ViewHolder(view);
            view.setTag(holder);
        }else{
            holder = (ViewHolder) view.getTag();
        }

        holder.txtTitle.setText(list.get(i).getName());
        holder.txtTime.setText(list.get(i).getCreatetime());
        return view;
    }

    static class ViewHolder {
        @BindView(R.id.txt_title)
        TextView txtTitle;
        @BindView(R.id.txt_time)
        TextView txtTime;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}

最后不要网络生成gen!!!









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值