Voglio salvare/richiamare un array intero utilizzando SharedPreferences, è possibile?Come posso memorizzare un array intero in SharedPreferences?
risposta
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()); }
È possibile salvare solo i valori primitivi in sharedPreference
. Utilizzare invece Sqlite
.
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;
}
Hai dimenticato di chiamare commit(). –
Hai ragione! aggiornato –
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;
}
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.
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.
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)
- 1. Salvataggio di un intero pacchetto di SharedPreferences
- 2. Come memorizzare un array in un cookie?
- 3. Come posso memorizzare i puntatori di funzione in un array?
- 4. Memorizzazione di un array di stringhe in SharedPreferences
- 5. Memorizzare un numero intero in un carattere * in C++
- 6. Come memorizzare un numero intero (10 cifre) intero?
- 7. Come memorizzare un array in mysql?
- 8. Come memorizzare un riferimento a un numero intero in C#?
- 9. Memorizzare un array multidimensionale in un cookie?
- 10. Come creare un array intero in Python?
- 11. Come posso memorizzare un valore float in un NSArray?
- 12. Come memorizzare un array restituito da un metodo in Java
- 13. Cancella intero array Python
- 14. Come utilizzare SharedPreferences in Xamarin.Android?
- 15. Come convertire un intero in un array in PHP?
- 16. Come memorizzare un array in un cookie JavaScript?
- 17. Un array intero come chiave per Dizionario
- 18. Utilizzare `SharedPreferences` per memorizzare il token di autenticazione
- 19. IOS: memorizzare un array con NSUserDefault
- 20. Ricerca della somma del sub-array in un array intero
- 21. Come memorizzare più tipi di dati in un array?
- 22. Come memorizzare i valori dal ciclo foreach in un array?
- 23. Come memorizzare un array di coppie in java?
- 24. Perl: taglia un array, senza creare un intero nuovo array
- 25. Come posso memorizzare un dizionario con RealmSwift?
- 26. Come posso memorizzare un UIImage in un NSDictionary?
- 27. Come analizzare ANR in sharedPreferences
- 28. memorizzare gli oggetti cvMat in un array - OpenCV - iPhone
- 29. Quanti dati posso memorizzare in un cookie
- 30. asp.net mvc - dove memorizzare userid - intero?
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). –
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 –