Las preferencias compartidas de Android no se guardan
He creado un fondo de pantalla en vivo para Android y estoy tratando de permitir que un usuario elija una imagen de su teléfono y la aplique como imagen de fondo, pero cuando inicio la actividad que inicia la intención de elegir las imágenes, mis preferencias compartidas no parecen guardar correctamente.
A continuación se muestra mi método onCreate de la actividad que inicio cuando los usuarios presionan el botón de preferencia, y el onActivityResult que obtiene la ruta de la imagen en el dispositivo (todo lo que parece funcionar). La impresión después de I confirmar las preferencias no imprime nada.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PICTURE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, 0);
preferences.edit().putString(SETTINGS_BACKGROUND_IMAGE, "okok");
preferences.edit().commit();
System.out.println("Image" + preferences.getString(SETTINGS_BACKGROUND_IMAGE, ""));
}
}
finish();
}
4 answers
Cree un nuevo Editor para estas preferencias, a través del cual puede hacer modificaciones a los datos en las preferencias y confirmación atómica esos cambios vuelven al objeto SharedPreferences.
Dado que es una nueva instancia de editor, su código debería ser más como este:
preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SETTINGS_BACKGROUND_IMAGE, "okok");
editor.commit();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-13 02:56:17
Pruebe otra forma de inicializar su variable SharedPreferences:
SharedPreferences sf = PreferenceManager.getDefaultSharedPreferences(this);
También puede encadenar la escritura a sf con sf.edit().putString(string, value).commit();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-13 03:51:57
En mi caso tuve que añadir editor.apply (); antes de comprometerse para trabajar.
Este es mi código:
preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SETTINGS_BACKGROUND_IMAGE, "okok");
editor.apply();//I added this line and started to work...
editor.commit();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-05 21:47:05
Bueno, basado en @zrgiu post, para mí solo funcionó añadiendo editor.clear();
antes de usar el Editor...so el código final será algo así como:
preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, 0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.putString(SETTINGS_BACKGROUND_IMAGE, "okok");
editor.commit();
;)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-22 13:17:12