2011-08-24 12 views

risposta

41

Si può cercare di farlo in questo modo:

  • Mettete i vostri numeri interi in una stringa, che delimita ogni int da un personaggio, ad esempio una virgola, e poi salvarle come una stringa:

    SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
    int[] list = new int[10]; 
    StringBuilder str = new StringBuilder(); 
    for (int i = 0; i < list.length; i++) { 
        str.append(list[i]).append(","); 
    } 
    prefs.edit().putString("string", str.toString()); 
    
  • Ricevere le s tring e analizzarlo usando StringTokenizer:

    String savedString = prefs.getString("string", ""); 
    StringTokenizer st = new StringTokenizer(savedString, ","); 
    int[] savedList = new int[10]; 
    for (int i = 0; i < 10; i++) { 
        savedList[i] = Integer.parseInt(st.nextToken()); 
    } 
    
+1

Si noti che questo metodo può essere utilizzato solo quando si dispone di una piccola quantità di dati, poiché le operazioni con le stringhe non sono efficienti. (ogni personaggio deve essere analizzato durante la lettura). –

+1

Secondo javadoc, l'uso di StringTokenizer è sconsigliato: http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html, utilizzare invece String.split(). Vedi qui http://stackoverflow.com/questions/6983856/why-is-stringtokenizer-deprecated –

0

È possibile salvare solo i valori primitivi in ​​sharedPreference. Utilizzare invece Sqlite.

14

non si può mettere in array sharedPrefs, ma si può aggirare:

public void storeIntArray(String name, int[] array){ 
    SharedPreferences.Editor edit= mContext.getSharedPreferences("NAME", Context.MODE_PRIVATE).edit(); 
    edit.putInt("Count_" + name, array.length); 
    int count = 0; 
    for (int i: array){ 
     edit.putInt("IntValue_" + name + count++, i); 
    } 
    edit.commit(); 
} 
public int[] getFromPrefs(String name){ 
    int[] ret; 
    SharedPreferences prefs = mContext.getSharedPreferences("NAME", Context.MODE_PRIVATE); 
    int count = prefs.getInt("Count_" + name, 0); 
    ret = new int[count]; 
    for (int i = 0; i < count; i++){ 
     ret[i] = prefs.getInt("IntValue_"+ name + i, i); 
    } 
    return ret; 
} 
+0

Hai dimenticato di chiamare commit(). –

+0

Hai ragione! aggiornato –

5

Ecco la mia versione, basata sulla risposta di Egor. Preferisco non usare StringBuilder a meno che non stia costruendo una stringa enorme, ma grazie a Egor per aver usato StringTokenizer - non ho fatto molto uso di questo in passato, ma è molto utile! Cordiali saluti, questo è andato nella mia classe di utilità:

public static void saveIntListPrefs(
    String name, Activity activity, List<Integer> list) 
{ 
    String s = ""; 
    for (Integer i : list) { 
    s += i + ","; 
    } 

    Editor editor = activity.getPreferences(Context.MODE_PRIVATE).edit(); 
    editor.putString(name, s); 
    editor.commit(); 
} 

public static ArrayList<Integer> readIntArrayPrefs(String name, Activity activity) 
{ 
    SharedPreferences prefs = activity.getPreferences(Context.MODE_PRIVATE); 
    String s = prefs.getString(name, ""); 
    StringTokenizer st = new StringTokenizer(s, ","); 
    ArrayList<Integer> result = new ArrayList<Integer>(); 
    while (st.hasMoreTokens()) { 
    result.add(Integer.parseInt(st.nextToken())); 
    } 
    return result; 
} 
3

due soluzioni:

(1) Utilizzare http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

E 'split/join funzioni che consentono di unire e dividere i numeri interi in una liners:

StringUtils.join([1, 2, 3], ';') = "1;2;3" 
StringUtils.split("1;2;3", ';') = ["1", "2", "3"] 

Dovreste ancora per convertire le stringhe di nuovo a numeri interi, però.

In realtà, per la scissione java.lang.String.split() funzionerà altrettanto bene: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

(2) Utilizzare lo SharedPreferences.putStringSet() (API 11):

SharedPreferences.Editor editor = preferences.edit(); 
    int count = this.intSet.size(); 
    if (count > 0) { 
     Set<String> theSet = new HashSet<String>(); 
     for (Long l : this.intSet) { 
      theSet.add(String.valueOf(l)); 
     } 
     editor.putStringSet(PREFS_KEY, theSet); 
    } else { 
     editor.remove(PREFS_KEY); 
    } 
    editor.commit(); 

E per farlo tornare:

Set<String> theSet = this.preferences.getStringSet(PREFS_KEY, null); 
    if (theSet != null && !theSet.isEmpty()) { 
     this.intSet.clear(); 
     for (String s : theSet) { 
      this.intSet.add(Integer.valueOf(s)); 
     } 
    } 

Questo codice non cattura gli NPE o NumberFormatExceptions perché l'intSet è altrimenti assicurato a no t contenere qualsiasi null. Ma ovviamente, se non puoi assicurarti che nel tuo codice dovresti circondarlo con un try/catch.

+0

Soluzione 2 è la strada da percorrere – Cobbles

+0

La seconda soluzione è buona, ma perderà l'ordine degli elementi. – blackwolf

+0

@blackwolf Provalo con 'java.util.SortedSet' - forse Android lo serializza correttamente. – Risadinha

1

Mi piace utilizzare JSON, che può essere memorizzato e recuperato come stringa, per rappresentare qualsiasi dato complesso in SharedPreferences. Così, nel caso di un array int:

public void setPrefIntArray(String tag, int[] value) 
{ 
    SharedPreferences.Editor prefEditor = PreferenceManager.getDefaultSharedPreferences(context) 
      .edit(); 

    String s; 
    try 
    { 
     JSONArray jsonArr = new JSONArray(); 
     for (int i : value) 
      jsonArr.put(i); 

     JSONObject json = new JSONObject(); 
     json.put(tag, jsonArr); 

     s = json.toString(); 
    } 
    catch(JSONException excp) 
    { 
     s = ""; 
    } 

    prefEditor.putString(tag, s); 
    prefEditor.commit(); 
} 

public int[] getPrefIntArray(String tag, int[] defaultValue) 
{ 
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); 

    String s = pref.getString(tag, ""); 

    try 
    { 
     JSONObject json = new JSONObject(new JSONTokener(s)); 
     JSONArray jsonArr = json.getJSONArray(tag); 

     int[] result = new int[jsonArr.length()]; 

     for (int i = 0; i < jsonArr.length(); i++) 
      result[i] = jsonArr.getInt(i); 

     return result; 
    } 
    catch(JSONException excp) 
    { 
     return defaultValue; 
    } 
} 

La bellezza è che la stessa idea può essere applicata a qualsiasi altra rappresentabile dati complessi come JSON.

0

Ecco come il "convertito al comma-separated String" soluzione poteva guardare in Kotlin, implementate come funzioni di estensione:

fun SharedPreferences.Editor.putIntArray(key: String, value: IntArray): SharedPreferences.Editor { 
    return putString(key, value.joinToString(
      separator = ",", 
      transform = { it.toString() })) 
} 

fun SharedPreferences.getIntArray(key: String): IntArray { 
    with(getString(key, "")) { 
     with(if(isNotEmpty()) split(',') else return intArrayOf()) { 
      return IntArray(count(), { this[it].toInt() }) 
     } 
    } 
} 

questo modo è possibile utilizzare putIntArray(String, IntArray) e getIntArray(String) proprio come l'altra put e metodi di :

val prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) 
prefs.edit().putIntArray(INT_ARRAY_TEST_KEY, intArrayOf(1, 2, 3)).apply() 
val intArray = prefs.getIntArray(INT_ARRAY_TEST_KEY) 
Problemi correlati