Android編程心得-SharedPreference中putStringset存取數據

在我們使用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(); 

 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( 
                        ","); 
            } 

 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(
      ",");
   }
}
}

 

 

 

 

 

You May Also Like