Android開發(fā)常用工具類: SPUtils SharedPreferences存儲

SharedPreferences

調(diào)用putParam 就能保存String, Integer, Boolean, Float, Long類型的參數(shù)
調(diào)用getParam就能獲取到保存在手機里面的數(shù)據(jù)

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Base64;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class SPUtils {
/**

  • 保存在手機里面的文件名
    */
    public static final String FILE_NAME = "share_data";

/**

  • 保存數(shù)據(jù)的方法,我們需要拿到保存數(shù)據(jù)的具體類型,然后根據(jù)類型調(diào)用不同的保存方法
    */
    public static void putParam(Context context, String key, Object object) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();

if (object instanceof String) {
  editor.putString(key, (String) object);
} else if (object instanceof Integer) {
  editor.putInt(key, (Integer) object);
} else if (object instanceof Boolean) {
  editor.putBoolean(key, (Boolean) object);
} else if (object instanceof Float) {
  editor.putFloat(key, (Float) object);
} else if (object instanceof Long) {
  editor.putLong(key, (Long) object);
} else {
  editor.putString(key, object.toString());
}
SharedPreferencesCompat.apply(editor);

}

    //保存對象

public static boolean setObjectToShare(Context context, Object object, String key) {
// TODO Auto-generated method stub
SharedPreferences share = PreferenceManager
.getDefaultSharedPreferences(context);
if (object == null) {
SharedPreferences.Editor editor = share.edit().remove(key);
return editor.commit();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
} catch (IOException e) {
e.printStackTrace();
return false;
}
// 將對象放到OutputStream中
// 將對象轉(zhuǎn)換成byte數(shù)組,并將其進行base64編碼
String objectStr = new String(Base64.encode(baos.toByteArray(),
Base64.DEFAULT));
try {
baos.close();
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SharedPreferences.Editor editor = share.edit();
// 將編碼后的字符串寫到base64.xml文件中
editor.putString(key, objectStr);
return editor.commit();
}

//獲取對象
public static Object getObjectFromShare(Context context, String key) {
SharedPreferences sharePre = PreferenceManager
.getDefaultSharedPreferences(context);
try {
String wordBase64 = sharePre.getString(key, "");
// 將base64格式字符串還原成byte數(shù)組
if (wordBase64 == null || wordBase64.equals("")) { // 不可少,否則在下面會報java.io.StreamCorruptedException
return null;
}
byte[] objBytes = Base64.decode(wordBase64.getBytes(),
Base64.DEFAULT);
ByteArrayInputStream bais = new ByteArrayInputStream(objBytes);
ObjectInputStream ois = new ObjectInputStream(bais);
// 將byte數(shù)組轉(zhuǎn)換成product對象
Object obj = ois.readObject();
bais.close();
ois.close();
return obj;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**

  • 得到保存數(shù)據(jù)的方法,我們根據(jù)默認值得到保存的數(shù)據(jù)的具體類型,然后調(diào)用相對于的方法獲取值
    */
    public static Object getParam(Context context, String key, Object defaultObject) {
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    if (defaultObject instanceof String) {
    return sp.getString(key, (String) defaultObject);
    } else if (defaultObject instanceof Integer) {
    return sp.getInt(key, (Integer) defaultObject);
    } else if (defaultObject instanceof Boolean) {
    return sp.getBoolean(key, (Boolean) defaultObject);
    } else if (defaultObject instanceof Float) {
    return sp.getFloat(key, (Float) defaultObject);
    } else if (defaultObject instanceof Long) {
    return sp.getLong(key, (Long) defaultObject);
    }
return null;

}

/**

  • 移除某個key值已經(jīng)對應的值
    */
    public static void remove(Context context, String key) {
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.remove(key);
    SharedPreferencesCompat.apply(editor);
    }

/**

  • 清除所有數(shù)據(jù)
    */
    public static void clear(Context context) {
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.clear();
    SharedPreferencesCompat.apply(editor);
    }

/**

  • 查詢某個key是否已經(jīng)存在
    */
    public static boolean contains(Context context, String key) {
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    return sp.contains(key);
    }

/**

  • 返回所有的鍵值對
    */
    public static Map<String, ?> getAll(Context context) {
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    return sp.getAll();
    }

/**

  • 創(chuàng)建一個解決SharedPreferencesCompat.apply方法的一個兼容類

*/
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) {
  }

  return null;
}

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

}
}

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

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

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