2011-09-09 6 views
12

Sto lavorando in android. Voglio rendere sharedpreference nel mio codice, ma non conosco il modo in cui posso creare un sharedpreference per array e come posso usare il valore di quel sharedpreference in un'altra classe.In che modo scrivere codice per rendere condivisionipreferenziali per array in Android?

Questo è il mio array in un ciclo for: - urls [i] = sitesList.getWebsite(). Get (i);

voglio rendere la preferenza di condivisione di questo array urls []. per favore suggeriscimi come posso scrivere il codice per dichiarare sharedpreference e come posso recuperare il valore di quel sharedpreference?

Grazie in anticipo.

risposta

50

putStringSet e getStringSet sono disponibili solo in API 11.

In alternativa si potrebbe serializzare gli array utilizzando JSON in questo modo:

public static void setStringArrayPref(Context context, String key, ArrayList<String> values) { 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); 
    SharedPreferences.Editor editor = prefs.edit(); 
    JSONArray a = new JSONArray(); 
    for (int i = 0; i < values.size(); i++) { 
     a.put(values.get(i)); 
    } 
    if (!values.isEmpty()) { 
     editor.putString(key, a.toString()); 
    } else { 
     editor.putString(key, null); 
    } 
    editor.commit(); 
} 

public static ArrayList<String> getStringArrayPref(Context context, String key) { 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); 
    String json = prefs.getString(key, null); 
    ArrayList<String> urls = new ArrayList<String>(); 
    if (json != null) { 
     try { 
      JSONArray a = new JSONArray(json); 
      for (int i = 0; i < a.length(); i++) { 
       String url = a.optString(i); 
       urls.add(url); 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 
    return urls; 
} 

Set e prelevare gli URL in questo modo:

// store preference 
ArrayList<String> list = new ArrayList<String>(Arrays.asList(urls)); 
setStringArrayPref(this, "urls", list); 

// retrieve preference 
list = getStringArrayPref(this, "urls"); 
urls = (String[]) list.toArray(); 
+0

Sta funzionando per me .. In realtà voglio esattamente questo tipo di soluzione .. Grazie a Jeff Gilfelf –

Problemi correlati