¿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
Respuesta
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.
¡Gracias! Probaré esto ASAP – cerealspiller
no se olvide de aceptar y/o votar la respuesta si esto ayudó;) – zarthross
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} –
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);
}
}
}
- 1. Android SharedPreferences en Fragment
- 2. Android: ¿Ver archivo SharedPreferences?
- 3. Limitaciones de Android SharedPreferences?
- 4. NullPointerException en SharedPreferences Android
- 5. android sharedpreferences establecer valor
- 6. ¿Qué es SharedPreferences en Android?
- 7. android - sharedpreferences return value nulo
- 8. Android SharedPreferences Copia de seguridad no funciona
- 9. Android: uso de SharedPreferences en una biblioteca
- 10. Android - SharedPreferences con el objeto serializable
- 11. Archivo SharedPreferences
- 12. cifrar datos en SharedPreferences
- 13. SharedPreferences a veces se eliminan
- 14. Android - ¿Cómo usar las SharedPreferences en la clase no activa?
- 15. ¿Cómo elimino SharedPreferences desde fuera de una aplicación de Android?
- 16. android-maven-plugin: método de implementación que no elimina SharedPreferences
- 17. Android: ¿Cómo reiniciar FirstRun SharedPreferences cuando mi aplicación se actualiza?
- 18. ¿Se pueden compartir SharedPreferences entre diferentes aplicaciones de Android?
- 19. SharedPreferences no se actualiza
- 20. SharedPreferences de diferente actividad
- 21. ¿Contexto de aplicación para SharedPreferences?
- 22. Opción múltiple ListView y SharedPreferences
- 23. Matriz de cadenas en SharedPreferences
- 24. obtener SharedPreferences de un servicio
- 25. Acceso a SharedPreferences sin contexto
- 26. Guarde los archivos de SharedPreferences en el directorio personalizado u obtenga el directorio predeterminado de SharedPreferences
- 27. ¿Cómo examinar SharedPreferences desde adb shell?
- 28. Tamaño máximo de la clase SharedPreferences
- 29. ¿El acceso a SharedPreferences consume mucho tiempo?
- 30. Marco de casos múltiples SharedPreferences/archivos
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
¿por qué quieres copiar las preferencias compartidas? Explica con más detalle qué intentas lograr y nos ayudará a dar una respuesta adecuada. – Kenny
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