SharedPreferences

一、获取SharedPreferences实例的方式

     1、Activity方式:public SharedPreferences getPreferences(int mode):用这种方式获取的SharedPreferences对象,读写

         都必须在同一个Activity中进行。

     2、ContextWrapper方式:public SharedPreferences getSharedPreferences(String name,int mode):用这种方式获取的是

         用户自定义的xml文件,可以在应用程序中任何地方进行,只要有ContextWrapper对象就行。

     3、PreferenceManager方式:public static SharedPreferences getDefaultSharedPreferences(Context context):用这种方

         式获取的是包名_preferences.xml文件,在应用程序中任何地方进行。

 二、特殊用法

      

在我们使用SharedPreference的时候,常用的就是存储配置文件信息,但有时我们需要存储多维数组信息的时候,就可以用到putStringSet。

下面是写方法:


[html]
public void SaveSiteinfoToXml() { 
    final SharedPreferences prefs = PreferenceManager 
            .getDefaultSharedPreferences(MainActivity.this); 
    Editor editor = prefs.edit(); 
    Set<String> siteno = new HashSet<String>(); 
    if (Unit_PublicVar.arr_DeatilContent != null) { 
        for (int i = 0; i < Unit_PublicVar.arr_DeatilContent.length; i++) { 
            siteno.add(Unit_PublicVar.arr_DeatilContent[i][0] + "," 
                    + Unit_PublicVar.arr_DeatilContent[i][1] + "," 
                    + Unit_PublicVar.arr_DeatilContent[i][2] + "," 
                    + Unit_PublicVar.arr_DeatilContent[i][3]); //  
 
        } 
    } 
    editor.putStringSet("站点信息", siteno); 
 
    editor.commit(); 

putStringset需要传入Set<String> 类型的参数  ,本函数的二维数组之前已经有值了,所以此处直接存储是没有问题的。

下面是读方法


[java]
   public void LoadParaFromXml() { 
        final SharedPreferences prefs = PreferenceManager 
                .getDefaultSharedPreferences(MainActivity.this); 
        Set<String> siteno = new HashSet<String>(); 
        siteno = prefs.getStringSet("站点信息", siteno); 
        if (siteno.size() > 0) {      
            String[] data = (String[]) siteno.toArray(new String[siteno.size()]);   //将SET转换为数组   
            Unit_PublicVar.arr_DeatilContent = new String[data.length][]; 
            for (int i = 0; i < data.length; i++) { 
                Unit_PublicVar.arr_DeatilContent[i] = data[i].trim().split( 
                        ","); 
            } 

三、特殊用法

     

Android3.0以上版本中 SharedPreferences新增了函数

  1. abstract Set<String>   getStringSet(String key, Set<String> defValues)  
  2. Retrieve a set of String values from the preferences.  
abstract Set<String>	 getStringSet(String key, Set<String> defValues)
Retrieve a set of String values from the preferences.

同时SharedPreferences.Editor中也新增了函数

  1. abstract SharedPreferences.Editor    putStringSet(String key, Set<String> values)  
  2. Set a set of String values in the preferences editor, to be written back once commit() is called.  
abstract SharedPreferences.Editor	 putStringSet(String key, Set<String> values)
Set a set of String values in the preferences editor, to be written back once commit() is called.

这样可以直接存储一个字符串集合,但是android3.0以前的版本中没有,如何在android2.3的系统中寻找一种替代他们的方式,我们可以猜想下上面两个函数的实现,直接看代码:

  1. public class SharedPreferencesHandler {  
  2.     final static String regularEx = "|";  
  3.   
  4.     public static Set<String> getStringSet(SharedPreferences prefs, String key,  
  5.             Set<String> defValues) {  
  6.         String str = prefs.getString(key, "");  
  7.         if (!str.isEmpty()) {  
  8.             String[] values = str.split(regularEx);  
  9.             if (defValues == null) {  
  10.                 defValues = new HashSet<String>();  
  11.                 for (String value : values) {  
  12.                     if (!value.isEmpty()) {  
  13.                         defValues.add(value);  
  14.                     }  
  15.                 }  
  16.             }  
  17.         }  
  18.         return defValues;  
  19.     }  
  20.   
  21.     public static SharedPreferences.Editor putStringSet(  
  22.             SharedPreferences.Editor ed, String key, Set<String> values) {  
  23.         String str = "";  
  24.         if (values != null | !values.isEmpty()) {  
  25.             Object[] objects = values.toArray();  
  26.             for (Object obj : objects) {  
  27.                 str += obj.toString();  
  28.                 str += regularEx;  
  29.             }  
  30.             ed.putString(key, str);  
  31.         }  
  32.         return ed;  
  33.     }  
  34. }  
public class SharedPreferencesHandler {
	final static String regularEx = "|";

	public static Set<String> getStringSet(SharedPreferences prefs, String key,
			Set<String> defValues) {
		String str = prefs.getString(key, "");
		if (!str.isEmpty()) {
			String[] values = str.split(regularEx);
			if (defValues == null) {
				defValues = new HashSet<String>();
				for (String value : values) {
					if (!value.isEmpty()) {
						defValues.add(value);
					}
				}
			}
		}
		return defValues;
	}

	public static SharedPreferences.Editor putStringSet(
			SharedPreferences.Editor ed, String key, Set<String> values) {
		String str = "";
		if (values != null | !values.isEmpty()) {
			Object[] objects = values.toArray();
			for (Object obj : objects) {
				str += obj.toString();
				str += regularEx;
			}
			ed.putString(key, str);
		}
		return ed;
	}
}

然后使用的时候可以这样存储和获取一个字符串的集合:

  1. final Set<String> snoozedIds = SharedPreferencesHandler  
  2.                     .getStringSet(prefs, PREF_SNOOZE_IDS, new HashSet<String>());  
  3.             // prefs.getStringSet(PREF_SNOOZE_IDS,   
  4.             // new HashSet<String>());   
  5.             snoozedIds.add(Integer.toString(id));  
  6.             final SharedPreferences.Editor ed = prefs.edit();  
  7.             SharedPreferencesHandler.putStringSet(ed, PREF_SNOOZE_IDS,  
  8.                     snoozedIds);  
  9.             // ed.putStringSet(PREF_SNOOZE_IDS, snoozedIds);   
  10.             ed.putLong(getAirPrefSnoozeTimeKey(id), time);  
  11.             ed.apply();  

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值