//新建个类写以下方法
private SqBeanDao dao;
//设置单例模式
private SqUtils() {}
private static SqUtils sqUtils;
public static SqUtils getSqUtils(){
synchronized (SqUtils.class){
if (sqUtils==null){
sqUtils=new SqUtils();
}
}
return sqUtils;
}
//初始化
public void init(Context context){
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "bw.db");
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster master=new DaoMaster(db);
dao = master.newSession().getSqBeanDao();
}
//插入缓存
public void insert(String key,String cache){
List<SqBean> list = dao.loadAll();//查询全部
boolean isHave=true;
for (int i = 0; i < list.size(); i++) {
SqBean b = list.get(i);
if(b.getKey().equals(key)){//意味着数据库里已经有了
isHave=false;
b.setValue(cache);
dao.update(b);//更新
}
}
if(isHave){
SqBean sqBean=new SqBean();
sqBean.setKey(key);
sqBean.setValue(cache);
dao.insert(sqBean);
}
}
//获取缓存
public String queryCache(String key){
List<SqBean> list = dao.loadAll();//查询全部
String cache=null;
for (int i = 0; i <list.size() ; i++) {
SqBean bean = list.get(i);
if(bean.getKey().equals(key)){
cache=bean.getValue();
break;
}
}
return cache;
}
//添加
public void add(SqBean bean){
dao.insert(bean);
}
//查询全部
public List<SqBean> loadAll(){
List<SqBean> sqliteBeans = dao.loadAll();
return sqliteBeans;
}
//根据key查询单个
public SqBean load(Long key){
SqBean bean = dao.load(key);
return bean;
}
//删除全部
public void deleteAll(){
dao.deleteAll();
}
//根据key删除单个
public void delete(Long key){
dao.deleteByKey(key);
}
//修改
public void updete(SqBean bean){
dao.update(bean);
}
//=================================================
//在需要缓存的页面
//第一次调用接口时调用以下方法
setCache(true,"index_movie_0",getActivity());
数据库缓存数据
最新推荐文章于 2022-08-10 12:33:41 发布