2014年11月15日 星期六

Android-將物件 存放 / 讀取 Cache

各位跟我一樣是開發新手的大大們
想必多少都會遇到想暫存資料
是圖片那還有很多資訊可找
但如果是自訂的物件呢?
用 SharedPreferences 又有型別的限制
讓人超級頭痛的
這幾天不斷的用G大神搜索,終於在GitHub找到超好用的Class
但前提是,必須要將物件序列化 implements Serializable


import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class SimpleObjectCache {

    public static void saveObject(Object object, String id,Context context) {
 
        try {
            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(
    new File(context.getCacheDir(), "") + "/"+id));
    
            out.writeObject(object);
            out.close();
   
        } catch (Exception e) {
            e.printStackTrace();
   
        }
    }

    public static Object loadObject(String id,Context context) 
   throws FileNotFoundException {
   
        Object object = null;
        ObjectInputStream in = null;
  
        try {
            in = new ObjectInputStream(new FileInputStream(
    new File(new File(context.getCacheDir(), "") + "/"+id)));
        
            object = in.readObject();
            in.close();
   
        }catch (IOException | ClassNotFoundException e){
            throw new FileNotFoundException();
   
        }
        return object;
  
    }
    
    public static Boolean removeObject(String id,Context context){
     File file = new File(new File(context.getCacheDir(), "") + "/"+id);
     return file.delete();
  
    }
}

* 服用方式
final String ID_BANDS = "bandsObejct";

// List of bands
ArrayList<String> bands = new ArrayList<String>();
bands.add("Arctic Monkeys");
bands.add("Led Zeppelin");
bands.add("Yann Tiersen");

// Saving
SimpleObjectCache.saveObject(bands, ID_BANDS, getApplicationContext());

// Retrieving
try {
    ArrayList<String> bandsTemp = (ArrayList<String>) SimpleObjectCache
            .loadObject(ID_BANDS, getApplicationContext());
    for (String string : bandsTemp) {
        Log.d("BANDS", string);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

// Deleting
Boolean wasRemoved = SimpleObjectCache.removeObject(ID_BANDS,
        getApplicationContext());

資料來源 : https://github.com/wesleiwpa/simple-object-cache-android

沒有留言:

張貼留言