24 octubre, 2018

Cómo crear SharedPreferences en Android

Para programa un gestor de preferencias en una app Android programaremos nuestra propia clase que administre las preferencias para guardar datos

Suscríbete a nuestro canal en Youtube

Suscríbirse

¿Cómo se crean las preferencias en Android Studio?

En esta ocasión vamos a hablar de la posibilidad de almacenar preferencias de usuario (SharedPreferences) en nuestra aplicación, utilizando la herramienta que nos facilita Android para ello.

Programando la clase SessionManager para administrar las preferencias en Android 

Usaremos una clase llamada sesionmanager.java

package app.kolibrin.clases;

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

public class SessionManager {

	private static SessionManager INSTANCE = null;
	private static String ID_STRING = "LoginActivity";
	private static String LOG_TAG = "SessionManager";
	
 // APP STANDARD KEY VALUES

	public static final String INSTALACION 		= "instalacion";
	public static final String RADIO 		= "radio";
	public static final String COMIDA 		= "comida";
	public static final String EDUCACION 	= "educacion";
	public static final String TURISMO 		= "turismo";
	public static final String VIAJES 		= "viajes";
	public static final String EVENTOS 		= "eventos";
	public static final String SERVICIOS 	= "servicios";
	public static final String SALUD 		= "salud";
	public static final String HOGAR 		= "hogar";
	
	private static SharedPreferences prefs;
	private static SharedPreferences.Editor edit;
	
	private SessionManager(Context ctx){
		prefs = ctx.getSharedPreferences(ID_STRING, Context.MODE_PRIVATE);
	}
	
	public static SessionManager getManager(Context ctx) {
		if (INSTANCE == null) {
			INSTANCE = new SessionManager(ctx);
		}
		return INSTANCE;
	}
	
	// saveKey methods
	/**
	 * Save an integer value in the default preferences
	 * @param key The name for the key-value pair, consider using one of the standard values
	 * @param value The integer to be stored
	 * @return The actual SessionManager singleton object
	 */
	public SessionManager saveKey(String key, int value) {
		checkStandarKey(key);
		edit = prefs.edit();
		edit.putInt(key, value);
		edit.commit();
		return INSTANCE;
		
	}
	
	/**
	 * Save a boolean value in the default preferences
	 * @param key The name for the key-value pair, consider using one of the standard values
	 * @param value The boolean to be stored
	 * @return The actual SessionManager singleton object
	 */
	public SessionManager saveKey(String key, boolean value) {
		checkStandarKey(key);
		edit = prefs.edit();
		edit.putBoolean(key, value);
		edit.commit();
		return INSTANCE;
	}
	
	/**
	 * Save a float value in the default preferences
	 * @param key The name for the key-value pair, consider using one of the standard values
	 * @param value The float to be stored
	 * @return The actual SessionManager singleton object
	 */
	public SessionManager saveKey(String key, float value) {
		
		checkStandarKey(key);
		
		edit = prefs.edit();
		edit.putFloat(key, value);
		edit.commit();
		
		return INSTANCE;
		
	}
	
	/**
	 * Save a long value in the default preferences
	 * @param key The name for the key-value pair, consider using one of the standard values
	 * @param value The long to be stored
	 * @return The actual SessionManager singleton object
	 */
	public SessionManager saveKey(String key, long value) {
		
		checkStandarKey(key);
		
		edit = prefs.edit();
		edit.putLong(key, value);
		edit.commit();
		
		return INSTANCE;
		
	}
	
	/**
	 * Save a string in the default preferences
	 * @param key The name for the key-value pair, consider using one of the standard values
	 * @param value The string to be stored
	 * @return The actual SessionManager singleton object
	 */
	public SessionManager saveKey(String key, String value) {
		
		checkStandarKey(key);
		
		edit = prefs.edit();
		edit.putString(key, value);
		edit.commit();
		
		return INSTANCE;
		
	}
	
	// getKey methods
	/**
	 * Retrieve an integer value from app's default preferences
	 * @param key The name of the value that is requested
	 * @return The key's value or -1 if key does not exists
	 */
	public int getIntKey(String key) {
		
		checkStandarKey(key);
		
		if (!prefs.contains(key)) {
			Log.e(LOG_TAG, "The requested key does not exists in preferences");
			return -1;
		}
		
		return prefs.getInt(key, -1);
		
	}
	
	/**
	 * Retrieve a boolean value from app's default preferences
	 * @param key The name of the value that is requested
	 * @return The key's value or false if key does not exists
	 */
	public boolean getBooleanKey(String key) {
		
		checkStandarKey(key);
		
		if (!prefs.contains(key)) {
			Log.e(LOG_TAG, "The requested key does not exists in preferences");
			return false;
		}
		
		return prefs.getBoolean(key, false);
		
	}
	
	/**
	 * Retrieve a float value from app's default preferences
	 * @param key The name of the value that is requested
	 * @return The key's value or -1 if key does not exists
	 */
	public float getFloatKey(String key) {
		
		checkStandarKey(key);
		
		if (!prefs.contains(key)) {
			Log.e(LOG_TAG, "The requested key does not exists in preferences");
			return -1f;
		}
		
		return prefs.getFloat(key, -1f);
		
	}



	/**
	 * Retrieve a long value from app's default preferences
	 * @param key The name of the value that is requested
	 * @return The key's value of -1 if key does not exists
	 */
	public long getLongKey(String key) {
		
		checkStandarKey(key);
		
		if (!prefs.contains(key)) {
			Log.e(LOG_TAG, "The requested key does not exists in preferences");
			return -1;
		}
		
		return prefs.getLong(key, -1);
		
	}
	
	/**
	 * Retrieve a string value from app's default preferences
	 * @param key The name of the value that is requested
	 * @return The key's value or an empty string if key does not exists
	 */
	public String getStringKey(String key) {
		
		checkStandarKey(key);
		
		if (!prefs.contains(key)) {
			Log.e(LOG_TAG, "The requested key does not exists in preferences");
			return "";
		}
		
		return prefs.getString(key, "");
		
	}
	
	/**
	 * Display an error message if passed key is not part of
	 * the standard key-set
	 * @param key The key to test
	 */

	private void checkStandarKey(String key) {
		if (!key.equals(INSTALACION)
				&& (!key.equals(COMIDA))
				&& (!key.equals(EDUCACION))
				&& (!key.equals(TURISMO))
				&& (!key.equals(VIAJES))
				&& (!key.equals(EVENTOS))
				&& (!key.equals(SERVICIOS))
				&& (!key.equals(SALUD))
				&& (!key.equals(HOGAR))
				&& (!key.equals(RADIO))) {
			Log.w(LOG_TAG, "The passed key is not part of the standars key-set. Consider use another one of the standar set");
		}
	}
}

 

Para usar esta clase debemos tener una actividad llamada MainActivity, el código parcial es :

Claramente se puede estudiar que controla si es la primera vez que se lanza la app, si es asi levanta la actividad llamada PreferenciasActivity, porque la configuración sessionManager.INSTALACION se crea por defecto con el valor false.

Dentro de MainActivity

if(SessionManager.getManager(getApplicationContext()).getBooleanKey(SessionManager.INSTALACION) )
            Config.mensaje(getApplicationContext(),"Bienvenido");
        else {
            SessionManager.getManager(getApplicationContext()).saveKey(SessionManager.INSTALACION,true);
            Intent i = new Intent(getApplicationContext(), PreferenciasActivity.class);
            startActivity(i);
        }

El código de la actividad PreferenciasActivity es:

public class PreferenciasActivity extends AppCompatActivity implements View.OnClickListener {

    private Switch comida,educacion,turismo,viajes,servicios,eventos,salud,hogar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preferencias);
        comida      =   findViewById(R.id.comida);
        educacion   =   findViewById(R.id.educacion);
        turismo     =   findViewById(R.id.turismo);
        viajes      =   findViewById(R.id.viajes);
        servicios   =   findViewById(R.id.servicios);
        eventos     =   findViewById(R.id.eventos);
        salud       =   findViewById(R.id.salud);
        hogar       =   findViewById(R.id.hogar);
        comida.setOnClickListener(this);
        educacion.setOnClickListener(this);
        turismo.setOnClickListener(this);
        viajes.setOnClickListener(this);
        servicios.setOnClickListener(this);
        eventos.setOnClickListener(this);
        salud.setOnClickListener(this);
        hogar.setOnClickListener(this);
        comida.setChecked(SessionManager.getManager(getApplicationContext()).getBooleanKey(SessionManager.COMIDA));
        educacion.setChecked(SessionManager.getManager(getApplicationContext()).getBooleanKey(SessionManager.EDUCACION));
        turismo.setChecked(SessionManager.getManager(getApplicationContext()).getBooleanKey(SessionManager.TURISMO));
        viajes.setChecked(SessionManager.getManager(getApplicationContext()).getBooleanKey(SessionManager.VIAJES));
        servicios.setChecked(SessionManager.getManager(getApplicationContext()).getBooleanKey(SessionManager.SERVICIOS));
        eventos.setChecked(SessionManager.getManager(getApplicationContext()).getBooleanKey(SessionManager.EVENTOS));
        salud.setChecked(SessionManager.getManager(getApplicationContext()).getBooleanKey(SessionManager.SALUD));
        hogar.setChecked(SessionManager.getManager(getApplicationContext()).getBooleanKey(SessionManager.HOGAR));
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.comida:
                boolean configuracion1 = comida.isChecked();
                Config.mensaje(getApplicationContext(),configuracion1+"");
                SessionManager.getManager(getApplicationContext()).saveKey(SessionManager.COMIDA,configuracion1);
                break;
            case R.id.educacion:
                boolean configuracion2 = educacion.isChecked();
                SessionManager.getManager(getApplicationContext()).saveKey(SessionManager.EDUCACION,configuracion2);
                break;
            case R.id.turismo:
                boolean configuracion3 = educacion.isChecked();
                SessionManager.getManager(getApplicationContext()).saveKey(SessionManager.TURISMO,configuracion3);
                break;
            case R.id.viajes:
                boolean configuracion4 = educacion.isChecked();
                SessionManager.getManager(getApplicationContext()).saveKey(SessionManager.VIAJES,configuracion4);
                break;
            case R.id.servicios:
                boolean configuracion5 = educacion.isChecked();
                SessionManager.getManager(getApplicationContext()).saveKey(SessionManager.SERVICIOS,configuracion5);
                break;
            case R.id.eventos:
                boolean configuracion6 = educacion.isChecked();
                SessionManager.getManager(getApplicationContext()).saveKey(SessionManager.EVENTOS,configuracion6);
                break;
            case R.id.salud:
                boolean configuracion7 = educacion.isChecked();
                SessionManager.getManager(getApplicationContext()).saveKey(SessionManager.SALUD,configuracion7);
                break;
            case R.id.hogar:
                boolean configuracion8 = educacion.isChecked();
                SessionManager.getManager(getApplicationContext()).saveKey(SessionManager.HOGAR,configuracion8);
                break;
        }
    }
}

La vista  xml correspondiente es : 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="app.PreferenciasActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="40dp"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:textSize="20dp"
            android:textStyle="bold"
            android:text="Preferencias" />

        <View
            android:layout_width="match_parent"
            android:background="@color/colorPrimaryDark"
            android:layout_margin="5dp"
            android:layout_height="1dp"/>

        <TextView
            android:layout_width="match_parent"
            android:text="Notificaciones que desees recibir"
            android:layout_height="wrap_content" />


        <Switch
            android:id="@+id/comida"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_gravity="center_horizontal"
            android:text="Comida" />

        <Switch
            android:id="@+id/educacion"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_gravity="center_horizontal"
            android:text="Educación" />

        <Switch
            android:id="@+id/turismo"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="5dp"
            android:text="Turismo" />

        <Switch
            android:id="@+id/viajes"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="5dp"
            android:text="Viajes" />

        <Switch
            android:id="@+id/servicios"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_gravity="center_horizontal"
            android:text="Servicios" />

        <Switch
            android:id="@+id/eventos"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_gravity="center_horizontal"
            android:text="Eventos" />

        <Switch
            android:id="@+id/salud"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_gravity="center_horizontal"
            android:text="Salud" />

        <Switch
            android:id="@+id/hogar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_gravity="center_horizontal"
            android:text="Hogar" />

        <View
            android:layout_width="match_parent"
            android:background="@color/colorPrimaryDark"
            android:layout_margin="5dp"
            android:layout_height="1dp"/>

        <TextView
            android:layout_width="match_parent"
            android:text="Radio de búsqueda"
            android:layout_height="wrap_content" />


        <RadioGroup
            android:id="@+id/opciones_pago"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <RadioButton
                android:id="@+id/radio_100"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="16dp"
                android:layout_margin="5dp"
                android:checked="true"
                android:text="100 mts" />

            <RadioButton
                android:id="@+id/radio_500"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="false"
                android:layout_margin="5dp"
                android:text="500 mts" />
            <RadioButton
                android:id="@+id/radio_1000"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="false"
                android:text="1000 mts" />
            <RadioButton
                android:id="@+id/radio_5000"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:checked="false"
                android:text="1000 mts" />
        </RadioGroup>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

 


Leido 3859 veces | 0 usuarios

Descarga del código fuente Android de Cómo crear SharedPreferences en Android

11 descargas

Para descargar el código crea una cuenta

Crear cuenta

Compartir link del tutorial con tus amigos


Android Básico App para un Restaurante

USD 10.00

Descarga del código fuente

Android Básico App para un Restaurante
Android PHP MySql App Restaurant

USD 12.00

Descarga del código fuente

Android PHP MySql App Restaurant
Lector QR en Android PHP y MySql

USD 10.00

Descarga del código fuente

Lector QR en Android PHP y MySql
App Minimarket con Scanner QR

USD 200.00

Descarga del código fuente

App Minimarket con Scanner QR

Más tutoriales de Android

Codea Applications

México, Colombia, España, Venezuela, Argentina, Bolivia, Perú

© Copyright Codea::App Cursos de Programación Online | LATAM | 2020 - 2025