2011-09-20 12 views
7

¿Hay alguna manera de copiar o duplicar una SharedPreference? ¿O tendré que obtener cada variable de una y luego ponerlas en otra?Android: Copiar/Duplicar SharedPreferences

+0

obtener cada variable de una y ponerlas en otra es solo la forma en que lo hago. Pero SharedPrefs se almacenan como un archivo xml, imagino que es posible que pueda copiar ese archivo completo y pegarlo con un nuevo nombre de alguna manera. Ese enfoque puede requerir un dispositivo rooteado para poder obtener flujos de entrada y salida configurados en la carpeta SharedPreferences de la aplicación. – FoamyGuy

+0

¿por qué quieres copiar las preferencias compartidas? Explica con más detalle qué intentas lograr y nos ayudará a dar una respuesta adecuada. – Kenny

+0

Mi aplicación almacena sus variables en una preferencia compartida. Tengo alrededor de 50 variables que cambian constantemente, en otras palabras, no se pueden codificar en la aplicación. Me gustaría poder dejar de lado estas variables para que el usuario de la aplicación pueda iniciar una nueva sesión y luego alternar entre las dos. Supongo que podría absorberlo y escribir todas las variables en otra preferencia compartida, pero sería mucho más fácil si pudiera hacer esto: savedSharedPreference = sharedPreference. LoL – cerealspiller

Respuesta

12

intentar algo como esto:

//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. 

Espero que esto ayude.

+0

¡Gracias! Probaré esto ASAP – cerealspiller

+3

no se olvide de aceptar y/o votar la respuesta si esto ayudó;) – zarthross

+1

esto debe aceptarse como la respuesta. También es posible que desee añadir: \t \t/* Configuración de usuario se hacen persistentes en la configuración de la actividad */ \t \t si (SystemUtils.getSDKVersion()> Build.VERSION_CODES.FROYO) { \t \t \t editor.apply(); \t \t} else { \t \t \t editor.commit(); \t \t} –

7

Aquí una versión que también admite conjuntos de cadenas.

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