- 论坛徽章:
- 0
|
简单的数据库缓存实现,有不足的地方请指出~
使用示例:
CacheHelper.init(this).setJson("url", "json");
CacheHelper.init(this).getJson("url", new Handler(){
@Override
public void handleMessage(Message msg) {
String json = (String) msg.obj;
}
});
CacheHelper.init(this).clear();- import android.content.ContentValues;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- import android.os.Handler;
- import android.os.Message;
-
- /**
- * 缓存数据库
- * @author lu
- *
- */
- public class CacheHelper extends SQLiteOpenHelper {
-
- private static final String tableName = "JSONCACHE";
- private static final String URL = "URL";
- private static final String JSON = "JSON";
- private static final String DATE = "DATE";
-
- public CacheHelper(Context context) {
- super(context, "cache.db", null, 1);
- }
-
- @Override
- public void onCreate(SQLiteDatabase db) {
- //建表jsoncache,字段:请求地址url、缓存数据json、时间date
- db.execSQL("CREATE TABLE "+tableName+" (ID INTEGER PRIMARY KEY AUTOINCREMENT, "+URL+" TEXT NOT NULL, "+JSON+" TEXT NOT NULL, "+DATE+" INTEGER NOT NULL )");
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- }
-
- private static CacheHelper helper = null;
- public static CacheHelper init(Context context){
- if (helper==null) {
- helper = new CacheHelper(context);
- }
- return helper;
- }
-
- /**储存缓存json*/
- public void setJson(final String url0,final String json){
- new Thread(){
- public void run() {
- String url = urlEncode(url0);
- ContentValues cv = new ContentValues();
- cv.put(URL, url);
- cv.put(JSON, json);
- cv.put(DATE, System.currentTimeMillis());
- helper.getReadableDatabase().delete(tableName, URL+"=?", new String[]{url});
- helper.getReadableDatabase().insert(tableName, null, cv);
- }
- }.start();
- }
-
- /**获取缓存json,以handler的obj返回(懒得写监听器了)*/
- public void getJson(final String url0,final Handler handler){
- new Thread(){
- public void run() {
- String url = urlEncode(url0);
- String result = null;
- Cursor c =
- helper.getReadableDatabase().query(tableName,
- null,
- URL+"=?",
- new String[]{url},
- null,
- null,
- null);
- if (c.moveToNext()) {
- result = c.getString(c.getColumnIndex(JSON));
- }
- Message msg = Message.obtain();
- msg.obj = result;
- handler.sendMessage(msg);
- }
- }.start();
- }
-
- /**缓存需要定时清空*/
- public void clear(){
- new Thread(){
- public void run() {
- helper.getReadableDatabase().delete(tableName, "ID>?", new String[]{"0"});
- }
- }.start();
- }
-
- /**url需要去掉token*/
- private String urlEncode(String url){
- String result = url.replaceAll("accessToken.*?\\&", "");
- if (result.contains("accessToken")) {//如果还没去掉,说明是在尾部
- result = result.replaceAll("\\&accessToken.*?$", "");
- }
- return result;
- }
-
- }
复制代码 |
|