1. 程式人生 > >運用fastjson+SharedPreferences 儲存、讀取複雜資料

運用fastjson+SharedPreferences 儲存、讀取複雜資料

儲存資料:
SharedPreferencesUtil.putString(getActivity(), getString(R.string.faxian_title),
        JSON.toJSONString));//tmpSubject是一個複雜的類

讀取:
	
String s = SharedPreferencesUtil.getString(getActivity(),getString(R.string.faxian_title),"");
if(!TextUtils.isEmpty(s)){
    mSubjectList = JSON.parseArray(s,Discovery.class);
}
//構建個通用的SharedPreferencesUtil方法,方法中包括:
/**
 * @serialField 儲存在手機裡面的檔名
 */
private static final String FILE_NAME = "share";

/**
 * todo 儲存資料String
 *
 * @param context 上下文聯絡選單
 * @param key     鍵
 * @param value   值
 */
public static void putString(Context context, String key, String value) {
    if(context == null) context = App.getContext();
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putString(key, value == null ? "" : value);
    editor.apply();
}


/**
 * todo 獲取資料的方法
 *
 * @param context      上下文聯絡選單
 * @param key          鍵
 * @param defaultValue 預設資料
 * @return String 資料
 */
public static String getString(Context context, String key, String defaultValue) {
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    return sp.getString(key, defaultValue);
}