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

来源:互联网 发布:抽拉式油烟机 知乎 编辑:程序博客网 时间:2024/06/15 20:43

//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;@Entitypublic 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!!!







原创粉丝点击