標籤:android style blog color 檔案 資料
1 /** 2 * SharedPreferences的一個工具類,調用setParam就能儲存String, Integer, Boolean, Float, Long類型的參數 3 * 同樣調用getParam就能擷取到儲存在手機裡面的資料 4 * @author xiaanming 5 * 6 */ 7 public class SharedPreferencesUtils { 8 /** 9 * 儲存在手機裡面的檔案名稱 10 */ 11 private static final String FILE_NAME = "share_date"; 12 13 14 /** 15 * 儲存資料的方法,我們需要拿到儲存資料的具體類型,然後根據類型調用不同的儲存方法 16 * @param context 17 * @param key 18 * @param object 19 */ 20 public static void setParam(Context context , String key, Object object){ 21 22 String type = object.getClass().getSimpleName(); 23 SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); 24 SharedPreferences.Editor editor = sp.edit(); 25 26 if("String".equals(type)){ 27 editor.putString(key, (String)object); 28 } 29 else if("Integer".equals(type)){ 30 editor.putInt(key, (Integer)object); 31 } 32 else if("Boolean".equals(type)){ 33 editor.putBoolean(key, (Boolean)object); 34 } 35 else if("Float".equals(type)){ 36 editor.putFloat(key, (Float)object); 37 } 38 else if("Long".equals(type)){ 39 editor.putLong(key, (Long)object); 40 } 41 42 editor.commit(); 43 } 44 45 46 /** 47 * 得到儲存資料的方法,我們根據預設值得到儲存的資料的具體類型,然後調用相對於的方法擷取值 48 * @param context 49 * @param key 50 * @param defaultObject 51 * @return 52 */ 53 public static Object getParam(Context context , String key, Object defaultObject){ 54 String type = defaultObject.getClass().getSimpleName(); 55 SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); 56 57 if("String".equals(type)){ 58 return sp.getString(key, (String)defaultObject); 59 } 60 else if("Integer".equals(type)){ 61 return sp.getInt(key, (Integer)defaultObject); 62 } 63 else if("Boolean".equals(type)){ 64 return sp.getBoolean(key, (Boolean)defaultObject); 65 } 66 else if("Float".equals(type)){ 67 return sp.getFloat(key, (Float)defaultObject); 68 } 69 else if("Long".equals(type)){ 70 return sp.getLong(key, (Long)defaultObject); 71 } 72 73 return null; 74 } 75 }
儲存資料:
SharedPreferencesUtils.setParam(this, "String", "xiaanming"); SharedPreferencesUtils.setParam(this, "int", 10); SharedPreferencesUtils.setParam(this, "boolean", true); SharedPreferencesUtils.setParam(this, "long", 100L); SharedPreferencesUtils.setParam(this, "float", 1.1f);
擷取資料:
1 SharedPreferencesUtils.getParam(TimerActivity.this, "String", ""); SharedPreferencesUtils.getParam(TimerActivity.this, "int", 0); 2 SharedPreferencesUtils.getParam(TimerActivity.this, "boolean", false); 3 SharedPreferencesUtils.getParam(TimerActivity.this, "long", 0L); 4 SharedPreferencesUtils.getParam(TimerActivity.this, "float", 0.0f);