SPUtils

/**
 * @author xzj
 * @date 2016/8/24 15:40.
 */

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.List;

/**
 * SharedPreferences工具類, 可以通過傳入實(shí)體對象保存其至SharedPreferences中,
 * 并通過實(shí)體的類型Class將保存的對象取出. 支持不帶泛型的對象以及List集合
 */
public class SPUtils {

    private static final String LIST_TAG = ".LIST";
    private static SharedPreferences sharedPreferences;
    private static Gson gson;

    /**
     * 使用之前初始化, 可在Application中調(diào)用
     * @param context 請傳入ApplicationContext避免內(nèi)存泄漏
     */
    public static void init(Context context) {
        sharedPreferences = context.getSharedPreferences("shared_files",
                Context.MODE_PRIVATE);
        gson = new Gson();
    }

    private static void checkInit() {
        if (sharedPreferences == null || gson == null) {
            throw new IllegalStateException("Please call init(context) first.");
        }
    }

    /**
     * 保存對象數(shù)據(jù)至SharedPreferences, key默認(rèn)為類名, 如
     * <pre>
     * PreferencesHelper.putData(saveUser);
     * </pre>
     * @param data 不帶泛型的任意數(shù)據(jù)類型實(shí)例
     */
    public static <T> void putData(T data) {
        putData(data.getClass().getName(), data);
    }

    /**
     * 根據(jù)key保存對象數(shù)據(jù)至SharedPreferences, 如
     * <pre>
     * PreferencesHelper.putData(key, saveUser);
     * </pre>
     * @param data 不帶泛型的任意數(shù)據(jù)類型實(shí)例
     */
    public static <T> void putData(String key, T data) {
        checkInit();
        if (data == null)
            throw new IllegalStateException("data should not be null.");
        sharedPreferences.edit().putString(key, gson.toJson(data)).apply();
    }

    /**
     * 保存List集合數(shù)據(jù)至SharedPreferences, 請確保List至少含有一個元素, 如
     * <pre>
     * PreferencesHelper.putData(users);
     * </pre>
     * @param data List類型實(shí)例
     */
    public static <T> void putData(List<T> data) {
        checkInit();
        if (data == null || data.size() <= 0)
            throw new IllegalStateException(
                    "List should not be null or at least contains one element.");
        Class returnType = data.get(0).getClass();
        sharedPreferences.edit().putString(returnType.getName() + LIST_TAG,
                gson.toJson(data)).apply();
    }

    /**
     * 將數(shù)據(jù)從SharedPreferences中取出, key默認(rèn)為類名, 如
     * <pre>
     * User user = PreferencesHelper.getData(key, User.class)
     * </pre>
     */
    public static <T> T getData(Class<T> clz) {
        return getData(clz.getName(), clz);
    }

    /**
     * 根據(jù)key將數(shù)據(jù)從SharedPreferences中取出, 如
     * <pre>
     * User user = PreferencesHelper.getData(User.class)
     * </pre>
     */
    public static <T> T getData(String key, Class<T> clz) {
        checkInit();
        String json = sharedPreferences.getString(key, "");
        return gson.fromJson(json, clz);
    }

    /**
     * 將數(shù)據(jù)從SharedPreferences中取出, 如
     * <pre>List<User> users = PreferencesHelper.getData(List.class, User.class)</pre>
     */
    public static <T> List<T> getData(Class<List> clz,  Class<T> gClz) {
        checkInit();
        String json = sharedPreferences.getString(gClz.getName() + LIST_TAG, "");
        return gson.fromJson(json, new TypeToken<List>(){}.getType());
    }

    /**
     * 簡易字符串保存, 僅支持字符串
     */
    public static void putString(String key, String data) {
        sharedPreferences.edit().putString(key, data).apply();
    }

    /**
     * 簡易字符串獲取, 僅支持字符串
     */
    public static String getString(String key) {
        return sharedPreferences.getString(key, "");
    }

    public static void putInt(String key, int data) {
        sharedPreferences.edit().putInt(key,data).apply();
    }

    public static int getInt(String key) {
        return sharedPreferences.getInt(key, -1);
    }

    public static void putBoolean(String key, boolean data) {
        sharedPreferences.edit().putBoolean(key,data).apply();
    }

    public static boolean getBoolean(String key,boolean defaultData) {
        return sharedPreferences.getBoolean(key, defaultData);
    }

    public static void putFloat(String key, float data) {
        sharedPreferences.edit().putFloat(key,data).apply();
    }

    public static float getFloat(String key,float defaultData) {
        return sharedPreferences.getFloat(key, defaultData);
    }

    public static void putLong(String key, long data) {
        sharedPreferences.edit().putLong(key,data).apply();
    }

    public static float getLong(String key,long defaultData) {
        return sharedPreferences.getLong(key, defaultData);
    }

    public static void clear() {
        sharedPreferences.edit().clear().apply();
    }

    /**
     * 刪除保存的對象
     */
    public static void remove(String key) {
        sharedPreferences.edit().remove(key).apply();
    }

    /**
     * 刪除保存的對象
     */
    public static void remove(Class clz) {
        remove(clz.getName());
    }

    /**
     * 刪除保存的數(shù)組
     */
    public static void removeList(Class clz) {
        sharedPreferences.edit().remove(clz.getName() + LIST_TAG).apply();
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 借鑒“煩惱即菩提”的表達(dá),這里的“痛楚即菩提”中的“即”是接近之意。 文︱崔崔陶子 小時候的一次班級活動,老...
    崔崔陶子閱讀 441評論 0 0
  • 為什么想起要給他寫段話,還是源自于那一天他哭了!那天早操我沒有及時去教室,等我急急忙忙走到教室門口時,孩子們已經(jīng)在...
    宋紅利閱讀 329評論 0 0
  • 春日遲遲,卉木萋萋。倉庚喈喈,采蘩祁祁。 三月的田地,是最美麗,最富有顏色,且最有生機(jī)的。 你或許看厭了油菜花,可...
    毛毛蟲媽咪閱讀 537評論 0 2
  • 2017年,明天即將開始我的寒假生活。 工作四年,我依舊擁有寒暑假,沒錯,我是一名人民教師。 四年前,我沒有意識到...
    安之騰閱讀 1,014評論 13 8

友情鏈接更多精彩內(nèi)容