Buscar..


Introducción

SharedPreferences proporciona una forma de guardar datos en el disco en forma de pares clave-valor .

Sintaxis

  • Método de contexto

    • Public SharedPreferences getSharedPreferences (nombre de cadena, modo int)
  • Metodo de actividad

    • Public SharedPreferences getPreferences ()
  • Métodos SharedPreferences

    • Public SharedPreferences.Editor edit ()
    • booleano público contiene ()
    • Mapa público <String,?> getAll ()
    • public boolean getBoolean (String key, boolean defValue)
    • public float getFloat (String key, float defValue)
    • public int getInt (String key, int defValue)
    • public long getLong (String key, long defValue)
    • public String getString (String key, String defValue)
    • conjunto público getStringSet (clave de cadena, conjunto defValues)
    • public void registerOnSharedPreferenceChangeListener (SharedPreferences.OnSharedPreferenceChangeListener listener)
    • public void unregisterOnSharedPreferenceChangeListener (SharedPreferences.OnSharedPreferenceChangeListener listener)
  • SharedPreferences. Métodos del editor

    • se aplica el vacío público ()
    • public boolean commit ()
    • Public SharedPreferences.Editor clear ()
    • Public SharedPreferences.Editor putBoolean (clave de cadena, valor booleano)
    • Public SharedPreferences.Editor putFloat (clave de cadena, valor flotante)
    • Public SharedPreferences.Editor putInt (clave de cadena, valor int)
    • Public SharedPreferences.Editor putLong (clave de cadena, valor largo)
    • Public SharedPreferences.Editor putString (clave de cadena, valor de cadena)
    • Public SharedPreferences.Editor putStringSet (clave de cadena, valores establecidos)
    • Public SharedPreferences.Editor remove (clave de cadena)

Parámetros

Parámetro Detalles
llave Una String no nula que identifica el parámetro. Puede contener espacios en blanco o no imprimibles. Esto solo se usa dentro de su aplicación (y en el archivo XML), por lo que no tiene que tener un espacio de nombre, pero es una buena idea tenerla como una constante en su código fuente. No lo localices.
desvalorizar Todas las funciones de obtención toman un valor predeterminado, que se devuelve si la clave dada no está presente en las SharedPreferences . No se devuelve si la clave está presente pero el valor tiene un tipo incorrecto: en ese caso, se obtiene una ClassCastException .

Observaciones

  • SharedPreferences no debe utilizarse para almacenar gran cantidad de datos. Para tales propósitos, es mucho mejor usar SQLiteDatabase .

  • SharedPreferences son solo procesos únicos, a menos que use el modo en desuso MODE_MULTI_PROCESS . Entonces, si su aplicación tiene múltiples procesos, no podrá leer las SharedPreferences del proceso principal en otro proceso. En tales casos, debe usar otro mecanismo para compartir datos entre procesos, pero no use MODE_MULTI_PROCESS ya que no es confiable y está en desuso.

  • Es mejor usar la instancia de SharedPreferences en la clase Singleton para acceder a todo el context la aplicación. Si desea usarlo solo para una Actividad en particular, vaya a getPreferences() .

  • Evite almacenar información confidencial en texto sin SharedPreferences mientras usa SharedPreferences ya que se puede leer fácilmente.

Documentacion oficial

https://developer.android.com/reference/android/content/SharedPreferences.html

Leer y escribir valores en SharedPreferences

public class MyActivity extends Activity {

    private static final String PREFS_FILE = "NameOfYourPrefrenceFile";
    // PREFS_MODE defines which apps can access the file
    private static final int PREFS_MODE = Context.MODE_PRIVATE;
    // you can use live template "key" for quickly creating keys
    private static final String KEY_BOOLEAN = "KEY_FOR_YOUR_BOOLEAN";
    private static final String KEY_STRING = "KEY_FOR_YOUR_STRING";
    private static final String KEY_FLOAT = "KEY_FOR_YOUR_FLOAT";
    private static final String KEY_INT = "KEY_FOR_YOUR_INT";
    private static final String KEY_LONG = "KEY_FOR_YOUR_LONG";

    @Override
    protected void onStart() {
        super.onStart();
    
        // Get the saved flag (or default value if it hasn't been saved yet)
        SharedPreferences settings = getSharedPreferences(PREFS_FILE, PREFS_MODE);
        // read a boolean value (default false)
        boolean booleanVal = settings.getBoolean(KEY_BOOLEAN, false);
        // read an int value (Default 0)
        int intVal = settings.getInt(KEY_INT, 0);
        // read a string value (default "my string")
        String str = settings.getString(KEY_STRING, "my string");
        // read a long value (default 123456)
        long longVal = settings.getLong(KEY_LONG, 123456);
        // read a float value (default 3.14f)
        float floatVal = settings.getFloat(KEY_FLOAT, 3.14f);
    }

    @Override
    protected void onStop() {
        super.onStop();
        
        // Save the flag
        SharedPreferences settings = getSharedPreferences(PREFS_FILE, PREFS_MODE);
        SharedPreferences.Editor editor = settings.edit();
        // write a boolean value
        editor.putBoolean(KEY_BOOLEAN, true);
        // write an integer value
        editor.putInt(KEY_INT, 123);
        // write a string
        editor.putString(KEY_STRING, "string value");
        // write a long value
        editor.putLong(KEY_LONG, 456876451);
        // write a float value
        editor.putFloat(KEY_FLOAT, 1.51f);
        editor.apply();
    }
}

getSharedPreferences() es un método de la clase de Context , que la Activity extiende. Si necesita acceder al método getSharedPreferences() desde otras clases, puede usar context.getSharedPreferences() con una referencia de objeto de Context de una Activity , View o Application .

Quitando llaves

private static final String MY_PREF = "MyPref";

// ...

SharedPreferences prefs = ...;

// ...

SharedPreferences.Editor editor = prefs.edit();
editor.putString(MY_PREF, "value");
editor.remove(MY_PREF);
editor.apply();

Después de apply() , prefs contiene "clave" -> "valor", además de lo que ya contenía. Aunque parece que agregué "clave" y luego la eliminé, la eliminación realmente sucede primero. Los cambios en el Editor se aplican todos de una vez, no en el orden en que los agregó. Todas las eliminaciones suceden antes que todas las puestas.

Implementando una pantalla de configuración usando SharedPreferences

Un uso de SharedPreferences es implementar una pantalla de "Configuración" en su aplicación, donde el usuario puede configurar sus preferencias / opciones. Me gusta esto:

Captura de pantalla

Una PreferenceScreen guarda las preferencias del usuario en SharedPreferences . Para crear una PreferenceScreen, necesitas algunas cosas:

Un archivo XML para definir las opciones disponibles:

Esto va en /res/xml/preferences.xml , y para la pantalla de configuración anterior, se ve así:

<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory
        android:title="General options">
        <CheckBoxPreference
            android:key = "silent_mode"
            android:defaultValue="false"
            android:title="Silent Mode"
            android:summary="Mute all sounds from this app" />

        <SwitchPreference
            android:key="awesome_mode"
            android:defaultValue="false"
            android:switchTextOn="Yes"
            android:switchTextOff="No"
            android:title="Awesome mode™"
            android:summary="Enable the Awesome Mode™ feature"/>

        <EditTextPreference
            android:key="custom_storage"
            android:defaultValue="/sdcard/data/"
            android:title="Custom storage location"
            android:summary="Enter the directory path where you want data to be saved. If it does not exist, it will be created."
            android:dialogTitle="Enter directory path (eg. /sdcard/data/ )"/>
    </PreferenceCategory>
</PreferenceScreen>

Esto define las opciones disponibles en la pantalla de configuración. Hay muchos otros tipos de Preference enumerados en la documentación de los Desarrolladores de Android en la Clase de Preferencias .

A continuación, necesitamos una Actividad para alojar nuestra interfaz de usuario de Preferencias . En este caso, es bastante corto, y se ve así:

package com.example.preferences;

import android.preference.PreferenceActivity;
import android.os.Bundle;

public class PreferencesActivity extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }
}

Extiende PreferenceActivity y proporciona la interfaz de usuario para la pantalla de preferencias. Puede iniciarse como una actividad normal, en este caso, con algo como:

Intent i = new Intent(this, PreferencesActivity.class);
startActivity(i);

No te olvides de agregar PreferencesActivity a tu AndroidManifest.xml .

Obtener los valores de las preferencias dentro de su aplicación es bastante simple, solo llame a setDefaultValues() primero, para establecer los valores predeterminados definidos en su XML, y luego obtenga las SharedPreferences predeterminadas. Un ejemplo:

//set the default values we defined in the XML
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    
//get the values of the settings options
boolean silentMode = preferences.getBoolean("silent_mode", false);
boolean awesomeMode = preferences.getBoolean("awesome_mode", false);
    
String customStorage = preferences.getString("custom_storage", "");

Recupere todas las entradas almacenadas de un archivo de SharedPreferences particular

El método getAll() recupera todos los valores de las preferencias. Podemos usarlo, por ejemplo, para registrar el contenido actual de las SharedPreferences :

private static final String PREFS_FILE = "MyPrefs";

public static void logSharedPreferences(final Context context) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
    Map<String, ?> allEntries = sharedPreferences.getAll();
    for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
        final String key = entry.getKey();
        final Object value = entry.getValue();
        Log.d("map values", key + ": " + value);
    } 
}

La documentación le advierte sobre la modificación de la Collection devuelta por getAll :

Tenga en cuenta que no debe modificar la colección devuelta por este método ni alterar ninguno de sus contenidos. La consistencia de sus datos almacenados no está garantizada si lo hace.

Escuchando cambios de SharedPreferences

SharedPreferences sharedPreferences = ...;
sharedPreferences.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);


private final SharedPreferences.OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        //TODO
    }
}

Tenga en cuenta:

  • El oyente disparará solo si el valor se agregó o cambió, establecer el mismo valor no lo llamará;
  • El oyente debe guardarse en una variable miembro y NO con una clase anónima, porque registerOnSharedPreferenceChangeListener almacena con una referencia débil, por lo que sería una recolección de basura;
  • En lugar de usar una variable miembro, la clase también puede implementarla directamente y luego llamar a registerOnSharedPreferenceChangeListener(this);
  • Recuerde anular el registro del oyente cuando ya no sea necesario con unregisterOnSharedPreferenceChangeListener .

Lectura y escritura de datos en SharedPreferences con Singleton

SharedPreferences Manager (Singleton) para leer y escribir todo tipo de datos.

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;

import java.lang.reflect.Type;

/**
 * Singleton Class for accessing SharedPreferences,
 * should be initialized once in the beginning by any application component using static
 * method initialize(applicationContext)
 */
public class SharedPrefsManager {
    
    private static final String TAG = SharedPrefsManager.class.getName();
    private SharedPreferences prefs;
    private static SharedPrefsManager uniqueInstance;
    public static final String PREF_NAME = "com.example.app";

    private SharedPrefsManager(Context appContext) {
        prefs = appContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    }

    /**
     * Throws IllegalStateException if this class is not initialized
     *
     * @return unique SharedPrefsManager instance
     */
    public static SharedPrefsManager getInstance() {
        if (uniqueInstance == null) {
            throw new IllegalStateException(
                    "SharedPrefsManager is not initialized, call initialize(applicationContext) " +
                            "static method first");
        }
        return uniqueInstance;
    }

    /**
     * Initialize this class using application Context,
     * should be called once in the beginning by any application Component
     *
     * @param appContext application context
     */
    public static void initialize(Context appContext) {
        if (appContext == null) {
            throw new NullPointerException("Provided application context is null");
        }
        if (uniqueInstance == null) {
            synchronized (SharedPrefsManager.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new SharedPrefsManager(appContext);
                }
            }
        }
    }

    private SharedPreferences getPrefs() {
        return prefs;
    }

    /**
     * Clears all data in SharedPreferences
     */
    public void clearPrefs() {
        SharedPreferences.Editor editor = getPrefs().edit();
        editor.clear();
        editor.commit();
    }

    public void removeKey(String key) {
        getPrefs().edit().remove(key).commit();
    }

    public boolean containsKey(String key) {
        return getPrefs().contains(key);
    }

    public String getString(String key, String defValue) {
        return getPrefs().getString(key, defValue);
    }

    public String getString(String key) {
        return getString(key, null);
    }

    public void setString(String key, String value) {
        SharedPreferences.Editor editor = getPrefs().edit();
        editor.putString(key, value);
        editor.apply();
    }

    public int getInt(String key, int defValue) {
        return getPrefs().getInt(key, defValue);
    }

    public int getInt(String key) {
        return getInt(key, 0);
    }

    public void setInt(String key, int value) {
        SharedPreferences.Editor editor = getPrefs().edit();
        editor.putInt(key, value);
        editor.apply();
    }

    public long getLong(String key, long defValue) {
        return getPrefs().getLong(key, defValue);
    }

    public long getLong(String key) {
        return getLong(key, 0L);
    }

    public void setLong(String key, long value) {
        SharedPreferences.Editor editor = getPrefs().edit();
        editor.putLong(key, value);
        editor.apply();
    }

    public boolean getBoolean(String key, boolean defValue) {
        return getPrefs().getBoolean(key, defValue);
    }

    public boolean getBoolean(String key) {
        return getBoolean(key, false);
    }

    public void setBoolean(String key, boolean value) {
        SharedPreferences.Editor editor = getPrefs().edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    public boolean getFloat(String key) {
        return getFloat(key, 0f);
    }

    public boolean getFloat(String key, float defValue) {
        return getFloat(key, defValue);
    }

    public void setFloat(String key, Float value) {
        SharedPreferences.Editor editor = getPrefs().edit();
        editor.putFloat(key, value);
        editor.apply();
    }

    /**
     * Persists an Object in prefs at the specified key, class of given Object must implement Model
     * interface
     *
     * @param key         String
     * @param modelObject Object to persist
     * @param <M>         Generic for Object
     */
    public <M extends Model> void setObject(String key, M modelObject) {
        String value = createJSONStringFromObject(modelObject);
        SharedPreferences.Editor editor = getPrefs().edit();
        editor.putString(key, value);
        editor.apply();
    }

    /**
     * Fetches the previously stored Object of given Class from prefs
     *
     * @param key                String
     * @param classOfModelObject Class of persisted Object
     * @param <M>                Generic for Object
     * @return Object of given class
     */
    public <M extends Model> M getObject(String key, Class<M> classOfModelObject) {
        String jsonData = getPrefs().getString(key, null);
        if (null != jsonData) {
            try {
                Gson gson = new Gson();
                M customObject = gson.fromJson(jsonData, classOfModelObject);
                return customObject;
            } catch (ClassCastException cce) {
                Log.d(TAG, "Cannot convert string obtained from prefs into collection of type " +
                        classOfModelObject.getName() + "\n" + cce.getMessage());
            }
        }
        return null;
    }

    /**
     * Persists a Collection object in prefs at the specified key
     *
     * @param key            String
     * @param dataCollection Collection Object
     * @param <C>            Generic for Collection object
     */
    public <C> void setCollection(String key, C dataCollection) {
        SharedPreferences.Editor editor = getPrefs().edit();
        String value = createJSONStringFromObject(dataCollection);
        editor.putString(key, value);
        editor.apply();
    }

    /**
     * Fetches the previously stored Collection Object of given type from prefs
     *
     * @param key     String
     * @param typeOfC Type of Collection Object
     * @param <C>     Generic for Collection Object
     * @return Collection Object which can be casted
     */
    public <C> C getCollection(String key, Type typeOfC) {
        String jsonData = getPrefs().getString(key, null);
        if (null != jsonData) {
            try {
                Gson gson = new Gson();
                C arrFromPrefs = gson.fromJson(jsonData, typeOfC);
                return arrFromPrefs;
            } catch (ClassCastException cce) {
                Log.d(TAG, "Cannot convert string obtained from prefs into collection of type " +
                        typeOfC.toString() + "\n" + cce.getMessage());
            }
        }
        return null;
    }

    public void registerPrefsListener(SharedPreferences.OnSharedPreferenceChangeListener listener) {
        getPrefs().registerOnSharedPreferenceChangeListener(listener);
    }

    public void unregisterPrefsListener(

            SharedPreferences.OnSharedPreferenceChangeListener listener) {
        getPrefs().unregisterOnSharedPreferenceChangeListener(listener);
    }

    public SharedPreferences.Editor getEditor() {
        return getPrefs().edit();
    }

    private static String createJSONStringFromObject(Object object) {
        Gson gson = new Gson();
        return gson.toJson(object);
    } 
}

interface Model implementada por las clases que van a Gson para evitar la ofuscación del programa.

public interface Model {
    
}

Reglas de progreso para la interfaz del Model :

-keep interface com.example.app.Model
-keep class * implements com.example.app.Model { *;}

Diferentes formas de instanciar un objeto de SharedPreferences

Puede acceder a SharedPreferences de varias maneras:

Obtenga el archivo predeterminado SharedPreferences:

import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

Obtener un archivo específico de SharedPreferences:

public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences prefs = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

Obtenga SharedPreferences de otra aplicación:

// Note that the other app must declare prefs as MODE_WORLD_WRITEABLE
final ArrayList<HashMap<String,String>> LIST = new ArrayList<HashMap<String,String>>();
Context contextOtherApp = createPackageContext("com.otherapp", Context.MODE_WORLD_WRITEABLE);
SharedPreferences prefs = contextOtherApp.getSharedPreferences("pref_file_name", Context.MODE_WORLD_READABLE); 

getPreferences (int) VS getSharedPreferences (String, int)

getPreferences(int)

devuelve las preferencias guardadas por Activity's class name como se describe en los documentos :

Recupere un objeto SharedPreferences para acceder a las preferencias que son privadas para esta actividad. Esto simplemente llama al método subyacente getSharedPreferences (String, int) pasando el nombre de clase de esta actividad como el nombre de las preferencias.

Mientras se usa el método getSharedPreferences (String name, int mode) , se devuelven las preferencias guardadas con el name dado. Como en los documentos:

Recupere y mantenga el contenido del 'nombre' del archivo de preferencias, devolviendo un SharedPreferences a través del cual puede recuperar y modificar sus valores.

Por lo tanto, si el valor que se está SharedPreferences en SharedPreferences se debe usar en toda la aplicación, se debe usar getSharedPreferences (String name, int mode) con un nombre fijo. Al usar getPreferences(int) devuelven / getPreferences(int) las preferencias que pertenecen a la Activity que lo llama.

Cometer vs. Aplicar

El método editor.apply() es asíncrono , mientras que editor.commit() es síncrono .

Obviamente, debe llamar a apply() o commit() .

2.3
SharedPreferences settings = getSharedPreferences(PREFS_FILE, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(PREF_CONST, true);
// This will asynchronously save the shared preferences without holding the current thread.
editor.apply();
SharedPreferences settings = getSharedPreferences(PREFS_FILE, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(PREF_CONST, true);
// This will synchronously save the shared preferences while holding the current thread until done and returning a success flag.
boolean result = editor.commit();

apply() se agregó en 2.3 (API 9), se compromete sin devolver un valor booleano que indique el éxito o el fracaso.

commit() devuelve true si el guardado funciona, falso de lo contrario.

apply() se agregó a medida que el equipo de desarrollo de Android notó que casi nadie se dio cuenta del valor de retorno, por lo que se aplica es más rápido ya que es asíncrono.

A diferencia de commit() , que escribe sus preferencias en el almacenamiento persistente sincrónicamente, apply() confirma sus cambios en las SharedPreferences en la memoria de inmediato, pero inicia una confirmación asíncrona en el disco y no se le notificará ningún error. Si otro editor en este SharedPreferences hace un commit() regular commit() mientras un apply() aún está pendiente, el commit() se bloqueará hasta que se completen todos los commit asíncronos (apply), así como cualquier otro commit de sincronización que pueda estar pendiente.

Tipos de datos soportados en SharedPreferences

SharedPreferences permite almacenar tipos de datos primitivos solamente ( boolean , float , long , int , String y string set ). No puede almacenar objetos más complejos en SharedPreferences y, como tal, realmente pretende ser un lugar para almacenar configuraciones de usuario o similar, no pretende ser una base de datos para mantener los datos del usuario (como guardar una lista de tareas pendientes de un usuario, por ejemplo).

Para almacenar algo en SharedPreferences utiliza una clave y un valor. La clave es cómo puede hacer referencia a lo que almacenó más tarde y los datos de valor que desea almacenar.

    String keyToUseToFindLater = "High Score";
    int newHighScore = 12938;
    //getting SharedPreferences & Editor objects 
    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    //saving an int in the SharedPreferences file
    editor.putInt(keyToUseToFindLater, newHighScore);
    editor.commit();

Almacenar, recuperar, eliminar y borrar datos de SharedPreferences

Crear SharedPreferences BuyyaPref

SharedPreferences pref = getApplicationContext().getSharedPreferences("BuyyaPref", MODE_PRIVATE); 
Editor editor = pref.edit();

Almacenamiento de datos como par KEY / VALUE

editor.putBoolean("key_name1", true);           // Saving boolean - true/false
editor.putInt("key_name2", 10);        // Saving integer
editor.putFloat("key_name3", 10.1f);    // Saving float
editor.putLong("key_name4", 1000);      // Saving long
editor.putString("key_name5", "MyString");  // Saving string
 
// Save the changes in SharedPreferences
editor.commit(); // commit changes

Obtener datos de SharedPreferences

Si el valor para la clave no existe, devuelva el segundo valor param (en este caso, nulo, es como el valor predeterminado)

pref.getBoolean("key_name1", null);         // getting boolean
pref.getInt("key_name2", null);             // getting Integer
pref.getFloat("key_name3", null);           // getting Float
pref.getLong("key_name4", null);            // getting Long
pref.getString("key_name5", null);          // getting String

Eliminar valor clave de SharedPreferences

editor.remove("key_name3"); // will delete key key_name3
editor.remove("key_name4"); // will delete key key_name4
 
// Save the changes in SharedPreferences
editor.commit(); // commit changes

Borrar todos los datos de SharedPreferences

 editor.clear();
 editor.commit(); // commit changes

Soporte pre-Honeycomb con StringSet

Aquí está la clase de utilidad:

public class SharedPreferencesCompat {

    public static void putStringSet(SharedPreferences.Editor editor, String key, Set<String> values) {
            if (Build.VERSION.SDK_INT >= 11) {
                while (true) {
                    try {
                        editor.putStringSet(key, values).apply();
                        break;
                    } catch (ClassCastException ex) {
                        // Clear stale JSON string from before system upgrade
                        editor.remove(key);
                    }
                }
            } else putStringSetToJson(editor, key, values);
    }

    public static Set<String> getStringSet(SharedPreferences prefs, String key, Set<String> defaultReturnValue) {
        if (Build.VERSION.SDK_INT >= 11) {
            try {
                return prefs.getStringSet(key, defaultReturnValue);
            } catch (ClassCastException ex) {
                // If user upgraded from Gingerbread to something higher read the stale JSON string
                return getStringSetFromJson(prefs, key, defaultReturnValue);
            }
        } else return getStringSetFromJson(prefs, key, defaultReturnValue);
    }

    private static Set<String> getStringSetFromJson(SharedPreferences prefs, String key, Set<String> defaultReturnValue) {
        final String input = prefs.getString(key, null);
        if (input == null) return defaultReturnValue;

        try {
            HashSet<String> set = new HashSet<>();
            JSONArray json = new JSONArray(input);
            for (int i = 0, size = json.length(); i < size; i++) {
                String value = json.getString(i);
                set.add(value);
            }
            return set;
        } catch (JSONException e) {
            e.printStackTrace();
            return defaultReturnValue;
        }
    }

    private static void putStringSetToJson(SharedPreferences.Editor editor, String key, Set<String> values) {
        JSONArray json = new JSONArray(values);
        if (Build.VERSION.SDK_INT >= 9)
            editor.putString(key, json.toString()).apply();
        else
            editor.putString(key, json.toString()).commit();
    }

    private SharedPreferencesCompat() {}
}

Un ejemplo para guardar preferencias como tipo de datos StringSet es:

Set<String> sets = new HashSet<>();
sets.add("John");
sets.add("Nicko");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferencesCompat.putStringSet(preferences.edit(), "pref_people", sets);

Para recuperarlos de nuevo:

Set<String> people = SharedPreferencesCompat.getStringSet(preferences, "pref_people", new HashSet<String>());

Referencia: preferencia de soporte de Android

Añadir filtro para EditTextPreference

Crea esta clase:

public class InputFilterMinMax implements InputFilter {

    private int min, max;

    public InputFilterMinMax(int min, int max) {
        this.min = min;
        this.max = max;
    }

    public InputFilterMinMax(String min, String max) {
        this.min = Integer.parseInt(min);
        this.max = Integer.parseInt(max);
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
            int input = Integer.parseInt(dest.toString() + source.toString());
            if (isInRange(min, max, input))
                return null;
        } catch (NumberFormatException nfe) { }
        return "";
    }

    private boolean isInRange(int a, int b, int c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }
}

Utilizar :

EditText compressPic = ((EditTextPreference) findPreference(getString("pref_key_compress_pic"))).getEditText();
compressPic.setFilters(new InputFilter[]{ new InputFilterMinMax(1, 100) });


Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow