2011-09-20 13 views
7

C'è un modo per copiare o duplicare un SharedPreference? O avrò bisogno di ottenere ogni variabile da uno e poi metterli in un altro?Android: Copia/Duplica SharedPreferences

+0

ottenere ogni variabile da uno e inserirli in un altro è solo il modo di cui ho conoscenza. Ma SharedPrefs è memorizzato come un file xml, immagino che potresti essere in grado di copiare l'intero file e incollarlo in qualche modo con un nuovo nome. Questo approccio potrebbe richiedere un dispositivo rooted per poter ottenere flussi di input e output impostati sulla cartella SharedPreferences dell'app. – FoamyGuy

+0

perché vuoi copiare i prefs condivisi? Spiega in modo un po 'più dettagliato che cosa stai cercando di ottenere e ci aiuterà a fornire una risposta adeguata. – Kenny

+0

La mia app memorizza le sue variabili in un riferimento condiviso. Ho circa 50 variabili che cambiano continuamente, in altre parole non possono essere codificate nell'app. Mi piacerebbe essere in grado di impostare queste variabili da parte in modo che l'utente dell'applicazione possa avviare una nuova sessione e quindi alternare tra le due. Suppongo che potrei succhiarlo e scrivere tutte le variabili su un altro sharedpreference, ma sarebbe molto più semplice se potessi fare questo: savedSharedPreference = sharedPreference. LoL – cerealspiller

risposta

12

provare qualcosa di simile:

//sp1 is the shared pref to copy to 
SharedPreferences.Editor ed = sp1.edit(); 
SharedPreferences sp = Sp2; //The shared preferences to copy from 
ed.clear(); // This clears the one we are copying to, but you don't necessarily need to do that. 
//Cycle through all the entries in the sp 
for(Entry<String,?> entry : sp.getAll().entrySet()){ 
Object v = entry.getValue(); 
String key = entry.getKey(); 
//Now we just figure out what type it is, so we can copy it. 
// Note that i am using Boolean and Integer instead of boolean and int. 
// That's because the Entry class can only hold objects and int and boolean are primatives. 
if(v instanceof Boolean) 
// Also note that i have to cast the object to a Boolean 
// and then use .booleanValue to get the boolean 
    ed.putBoolean(key, ((Boolean)v).booleanValue()); 
else if(v instanceof Float) 
    ed.putFloat(key, ((Float)v).floatValue()); 
else if(v instanceof Integer) 
    ed.putInt(key, ((Integer)v).intValue()); 
else if(v instanceof Long) 
    ed.putLong(key, ((Long)v).longValue()); 
else if(v instanceof String) 
    ed.putString(key, ((String)v));   
} 
ed.commit(); //save it. 

Spero che questo aiuti.

+0

Grazie! Proverò questo al più presto – cerealspiller

+3

non dimenticare di accettare e/o modificare la risposta se è stata d'aiuto;) – zarthross

+1

questa dovrebbe essere accettata come risposta. Inoltre si potrebbe desiderare di aggiungere: \t \t/* Impostazioni utente sono realizzati persistente in Impostazioni Attività */ \t \t se (SystemUtils.getSDKVersion()> Build.VERSION_CODES.FROYO) { \t \t \t editor.apply(); \t \t} else { \t \t \t editor.commit(); \t \t} –

7

Qui una versione che supporta anche set di stringhe.

public static void copySharedPreferences(SharedPreferences fromPreferences, SharedPreferences toPreferences) { 
    copySharedPreferences(fromPreferences, toPreferences, true); 
} 

public static void copySharedPreferences(SharedPreferences fromPreferences, SharedPreferences toPreferences, boolean clear) { 

    SharedPreferences.Editor editor = toPreferences.edit(); 
    if (clear) { 
     editor.clear(); 
    } 
    copySharedPreferences(fromPreferences, editor); 
    editor.commit(); 
} 

@TargetApi(Build.VERSION_CODES.HONEYCOMB) 
@SuppressWarnings({"unchecked", "ConstantConditions"}) 
public static void copySharedPreferences(SharedPreferences fromPreferences, SharedPreferences.Editor toEditor) { 

    for (Map.Entry<String, ?> entry : fromPreferences.getAll().entrySet()) { 
     Object value = entry.getValue(); 
     String key = entry.getKey(); 
     if (value instanceof String) { 
      toEditor.putString(key, ((String) value)); 
     } else if (value instanceof Set) { 
      toEditor.putStringSet(key, (Set<String>) value); // EditorImpl.putStringSet already creates a copy of the set 
     } else if (value instanceof Integer) { 
      toEditor.putInt(key, (Integer) value); 
     } else if (value instanceof Long) { 
      toEditor.putLong(key, (Long) value); 
     } else if (value instanceof Float) { 
      toEditor.putFloat(key, (Float) value); 
     } else if (value instanceof Boolean) { 
      toEditor.putBoolean(key, (Boolean) value); 
     } 
    } 
} 
Problemi correlati