(一)、个人习惯写BD工具类
public class DBTools { private class DataOpenHelper extends sqliteOpenHelper { public DataOpenHelper(Context context) { super(context,"SYData.db",null,1); } @Override public void onCreate(sqliteDatabase db) { db.execsql("create table data(id integer primary key,json text)"); db.execsql("insert into data values(?,?)",new String[] { "" + 1,"" }); db.execsql("insert into data values(?,new String[] { "" + 2,"" }); } @Override public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) { } } /** * 保存缓存 */ public void saveJson(Context context,int id,String json) { DataOpenHelper helper = new DataOpenHelper(context); sqliteDatabase db = helper.getWritableDatabase(); db.execsql("update data set json=? where id=?",new String[] { json,"" + id }); db.close(); } /** * 读取缓存 */ public String readJson(Context context,int id) { DataOpenHelper helper = new DataOpenHelper(context); sqliteDatabase db = helper.getWritableDatabase(); Cursor cursor = db.rawQuery("select json from data where id = ?",new String[] { "" + id }); boolean b = cursor.moveToFirst(); if (b) { String json = cursor.getString(cursor.getColumnIndex("json")); return json; } db.close(); return ""; } }(二)、封装一些方法
/** * 缓存机制(即,从本地读取数据或网上下载数据) */ private void getDataOrUpdata() { // 读取本地缓存 String result_hand = dbTools.readJson(getActivity(),1); String result_hot = dbTools.readJson(getActivity(),2); if (!result_hand.equals("") && !result_hot.equals("")) { dealJsonHeadData(result_hand); dealJsonHotData(result_hot); return; } // 网上下载数据 if (isNetworkAble()) { getDataFromServer(); } } // 判断网络是否连接是否可用 private boolean isNetworkAble() { ConnectivityManager manager = (ConnectivityManager) getActivity() .getSystemService(Context.CONNECTIVITY_SERVICE); if (manager != null) { NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null && info.isAvailable()) { return true; } } return false; }原文链接:https://www.f2er.com/sqlite/199630.html