2011-08-24 33 views

Respuesta

41

Usted puede tratar de hacerlo de esta manera:

  • Ponga sus números enteros en una cadena, delimitando cada int por un personaje, por ejemplo, una coma, y ​​luego guardarlos como una cadena:

    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()); 
    
  • Obtener los s Tring y analizarlo 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

Tenga en cuenta que este método podría usarse solo cuando tiene poca cantidad de datos, ya que las operaciones de cadena no son eficientes. (cada personaje debe ser analizado al leer). –

+1

De acuerdo con javadoc, no se recomienda el uso de StringTokenizer: http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html, use String.split() en su lugar. Consulte aquí http://stackoverflow.com/questions/6983856/why-is-stringtokenizer-deprecated –

0

Solo puede guardar valores primitivos en sharedPreference. Use Sqlite en su lugar.

14

no se puede poner en matrices sharedPrefs, pero se puede solucionar:

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

Ha olvidado llamar a commit(). –

+0

¡Tienes razón! se actualizó –

5

aquí está mi versión, basado en la respuesta de Egor. Prefiero no usar StringBuilder a menos que esté creando una cadena enorme, pero gracias a Egor por usar StringTokenizer, no he usado mucho esto en el pasado, ¡pero es muy útil! Para su información, esto fue en mi clase de utilidad:

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

dos soluciones:

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

Se ha dividido/unirse a las funciones que le permiten unirse y dividir los números enteros en trazadores de líneas uno:

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

Aún así tendría que convertir las cuerdas en enteros.

En realidad, para dividir java.lang.String.split() funcionará igual de bien: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

(2) Utilice el 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(); 

Y para recuperarla:

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)); 
     } 
    } 

Este código no capta los NPE o NumberFormatExceptions porque intSet está asegurado a no t contiene cualquier nulo. Pero, por supuesto, si no puede asegurar que en su código debe rodear esto con un try/catch.

+0

La solución 2 es el camino a seguir – Cobbles

+0

La segunda solución es agradable, pero perderá el orden de los elementos. – blackwolf

+0

@blackwolf Inténtalo con 'java.util.SortedSet' - tal vez Android lo serialice correctamente. – Risadinha

1

Me gusta usar JSON, que se puede almacenar y recuperar como una cadena, para representar cualquier dato complejo en SharedPreferences. Así, en el caso de una matriz 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 belleza es que la misma idea se puede aplicar a cualquier otro representable datos complejos como JSON.

0

Así es como el "convertir al separada por comas de cuerda" solución podría mirar en Kotlin, implementado como funciones de extensión:

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() }) 
     } 
    } 
} 

esa manera se puede utilizar putIntArray(String, IntArray) y getIntArray(String) igual que el otro puesto y métodos establecidos :

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) 
Cuestiones relacionadas