Android之SharedPreferences管理類AppPreferences

Android中對SharedPreferences管理的工具類,喜歡這種寫法。

public class AppPreferences {

public static class PreferenceKey {
    public final static String SP_NAME_NAME = "app_config";
 // public static final String TEST_KEY = "test_key";
}

private static AppPreferences appPreferences;
private SharedPreferences preferences;

private AppPreferences() {
    preferences = BaseApplication.getInstance().sharereferences;
}

public static AppPreferences instance() {
    if (appPreferences == null) {
        appPreferences = new AppPreferences();
    }
    return appPreferences;
}

public void put(String keyName, Object value) {
    SharedPreferences.Editor editor = preferences.edit();
    if (value instanceof String) {
        editor.putString(keyName, (String) value);
    } else if (value instanceof Integer) {
        editor.putInt(keyName, (Integer) value);
    } else if (value instanceof Boolean) {
        editor.putBoolean(keyName, (Boolean) value);
    } else if (value instanceof Float) {
        editor.putFloat(keyName, (Float) value);
    } else if (value instanceof Long) {
        editor.putLong(keyName, (Long) value);
    } else {
        editor.putString(keyName, value.toString());
    }
    editor.apply();
}

public Object get(String keyName, Object defaultValue) {
    if (defaultValue instanceof String) {
        return preferences.getString(keyName, (String) defaultValue);
    } else if (defaultValue instanceof Integer) {
        return preferences.getInt(keyName, (Integer) defaultValue);
    } else if (defaultValue instanceof Boolean) {
        return preferences.getBoolean(keyName, (Boolean) defaultValue);
    } else if (defaultValue instanceof Float) {
        return preferences.getFloat(keyName, (Float) defaultValue);
    } else if (defaultValue instanceof Long) {
        return preferences.getLong(keyName, (Long) defaultValue);
    }
    return null;
}

/**
 * 保存一個(gè)實(shí)體類,類名為key
 */
public void putObject(Object obj) {
    putObject(obj.getClass().getName(), obj);
}

/**
 * 獲取一個(gè)存儲實(shí)體類
 */
public <T> T getObject(Class<T> c) {
    return getObject(c.getName(), c);
}

/**
 * 保存一個(gè)實(shí)體類
 *
 * @param key    key
 * @param object object
 */
public void putObject(String key, Object object) {
    if (object == null) {
        return;
    }
    String value = (new Gson()).toJson(object);
    preferences.edit().putString(key, value).apply();
}

/**
 * 獲取一個(gè)存儲實(shí)體類
 *
 * @param key key
 * @param c   c
 * @param <T> T
 * @return <T> T
 */
public <T> T getObject(String key, Class<T> c) {
    String value = preferences.getString(key, "");
    if (TextUtils.isEmpty(value)) {
        return null;
    }
    T t = (new Gson()).fromJson(value, c);
    return t;
}

/**
 * 保存List
 *
 * @param key      key
 * @param datalist list
 */
public <T> void putDataList(String key, List<T> datalist) {
    if (null == datalist || datalist.size() <= 0) {
        return;
    }
    Gson gson = new Gson();
    // 轉(zhuǎn)換成json數(shù)據(jù),再保存
    String strJson = gson.toJson(datalist);
    preferences.edit().putString(key, strJson).apply();
}

/**
 * 獲取List
 *
 * @param key key
 * @return List
 */
public <T> List<T> getDataList(String key, Class<T> clazz) {
    String strJson = preferences.getString(key, null);
    if (null == strJson) {
        return null;
    }
    Type type = new TypeToken<ArrayList<JsonObject>>() {
    }.getType();
    ArrayList<JsonObject> jsonObjects = new Gson().fromJson(strJson, type);
    ArrayList<T> arrayList = new ArrayList<>();
    for (JsonObject jsonObject : jsonObjects) {
        arrayList.add(new Gson().fromJson(jsonObject, clazz));
    }
    return arrayList;

}

/**
 * 移除某個(gè)key值對應(yīng)的值
 *
 * @param key key
 */
public void remove(String key) {
    preferences.edit().remove(key).apply();
}

/**
 * 清除所有數(shù)據(jù)
 */
public void clearAll() {
    preferences.edit().clear().apply();
}

/**
 * 查詢某個(gè)key是否已經(jīng)存在
 *
 * @param key key
 * @return boolean
 */
public boolean contains(String key) {
    return preferences.contains(key);
}

/**
 * 獲取所有的鍵值對
 *
 * @return 所有的鍵值對
 */
public Map<String, ?> getAllKeyValue() {
    return preferences.getAll();
}

/**
 * 創(chuàng)建一個(gè)解決SharedPreferencesCompat.apply方法的一個(gè)兼容類
 */
private static class SharedPreferencesCompat {
    private static final Method sApplyMethod = findApplyMethod();

    /**
     * 反射查找apply的方法
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    private static Method findApplyMethod() {
        try {
            Class clz = SharedPreferences.Editor.class;
            return clz.getMethod("apply");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 如果找到則使用apply執(zhí)行,否則使用commit
     */
    public static void apply(SharedPreferences.Editor editor) {
        try {
            if (sApplyMethod != null) {
                sApplyMethod.invoke(editor);
                return;
            }
        } catch (IllegalArgumentException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        editor.commit();
    }
}}

SharedPreferencesCompat 在代碼中實(shí)際上沒調(diào)用到,網(wǎng)上找的資料為了兼容而寫的,需要用的時(shí)候就用吧,可以參考寫出其他兼容方法,O(∩_∩)O哈哈~

BaseApplication中:

截圖

雙十一馬上就要到了,啊啊啊啊??!剁手剁手剁手~~~看花眼了,我要控制我寄幾?。?!

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

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

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