Android: Guardar Objetos en las Preferencias

Partimos de un ejemplo para explicar cómo podemos guardar un objeto en las preferencias de Android.

1- Lo que haremos es utilizar Gson para serializar el bean como un Json y guardarlo en las preferencias de tu app en Android.

Necesitamos agregar esta dependencia **com.google.code.gson:gson:2.3.1  **en nuestro archivo  build.gradle

Encontraras la última numero de versión en [https://github.com/google/gson]1

 

    dependencies {
       compile fileTree(dir: 'libs', include: ['*.jar'])
       compile 'com.android.support:appcompat-v7:22.2.0'
       compile 'com.google.code.gson:gson:2.3.1'
    }

 

2-Creamos nuestra clase e indicamos qué atributos serán serializados por Gson

 

import com.google.gson.annotations.SerializedName;

/**
* Created by Gustavo Peiretti on 8/5/15.
*/
public class Person {

   @SerializedName("name")
   private String name;

   @SerializedName("mail")
   private String mail;

   // getters and setters
}

3- Ahora crearemos nuestra clase que se encargará de persistir nuestro objeto Person en las preferencias.

Aquí tenemos dos métodos, el primero save() que se encargará de convertir nuestro objeto Person en un String Json y luego lo persistirá en las preferencias dentro del key creado para tal fin.

El segundo método getPerson() buscará utilizando el key y devolverá el objeto, previo a deserializar y  convertir el Json en el objeto destino.

 

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.google.gson.Gson;

public class SettingPreferences {

   private static final String PERSON_PREFERENCE_KEY = "PERSON_PREFERENCE_KEY";
   private final Context context;

   public SettingPreferences(Context context) {
       this.context = context;
   }

   public void save(Person person) {
       SharedPreferences.Editor edit = getSharedPreferences().edit();
       String json = new Gson().toJson(person);
       edit.putString(PERSON_PREFERENCE_KEY,json);
       edit.commit();
   }

   public Person getPerson() {
       String json = getSharedPreferences().getString(PERSON_PREFERENCE_KEY,null);
       if(json == null){
return new Person();
       }
       Person person = new Gson().fromJson(json, Person.class);
       return person;
   }

   private SharedPreferences getSharedPreferences(){
       SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
       return preferences;
   }

}

 

4- Para probar nuestra aplicación crearemos un Activity muy simple donde pediremos que se ingrese nombre y mail, el cual persistiremos y recuperaremos.

Agregaremos a nuestro xml dos EditText y para guardar luego nuestro objeto Person

 

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
       android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
       android:paddingRight="@dimen/activity_horizontal_margin"
       android:paddingTop="@dimen/activity_vertical_margin"
       android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    
       <Button
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="Save"
           android:id="@+id/buttonSave"
           android:layout_centerVertical="true"
           android:layout_alignParentLeft="true"
           android:layout_alignParentStart="true" />
    
       <EditText
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:id="@+id/editTextName"
           android:layout_alignParentLeft="true"
           android:layout_alignParentStart="true"
           android:layout_marginTop="57dp"
           android:text="Name..."/>
    
       <EditText
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:id="@+id/editTextMail"
           android:layout_alignParentLeft="true"
           android:layout_alignParentStart="true"
           android:text="Mail..."
           android:layout_below="@+id/editTextName" />
    
    </RelativeLayout>

 

Nuestra clase quedará así.  Vemos que al iniciar traeremos de las preferencias settingPreferences.getPerson() y setearemos los valores en los EditText lo que nos mostrará en pantalla el ultimo valor seteados de Person.

Por último el método savePerson() se encargará de setear los valores desde el EditText a Person y luego persistirlos en las preferencias.

 

package com.gustavopeiretti.saveobjectinpreference;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

   private SettingPreferences settingPreferences;

   private Person person;

   private EditText editTextName;
   private EditText editTextMail;
   private Button buttonSave;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       settingPreferences = new SettingPreferences(this.getApplicationContext());

       person = settingPreferences.getPerson();

       editTextName = (EditText) findViewById(R.id.editTextName);
       editTextMail = (EditText) findViewById(R.id.editTextMail);
       buttonSave =  (Button) findViewById(R.id.buttonSave);

       editTextName.setText(person.getName());
       editTextMail.setText(person.getMail());

       buttonSave.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               savePerson();
           }
       });

   }

   private void savePerson() {
       person.setName(editTextName.getText().toString());
       person.setMail(editTextMail.getText().toString());
       settingPreferences.save(person);
       Toast.makeText(getApplicationContext(),"Person saved..",Toast.LENGTH_SHORT).show();
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
       // Inflate the menu; this adds items to the action bar if it is present.
       getMenuInflater().inflate(R.menu.menu_main, menu);
       return true;
   }

   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
       // Handle action bar item clicks here. The action bar will
       // automatically handle clicks on the Home/Up button, so long
       // as you specify a parent activity in AndroidManifest.xml.
       int id = item.getItemId();

       //noinspection SimplifiableIfStatement
       if (id == R.id.action_settings) {
           return true;
       }

       return super.onOptionsItemSelected(item);
   }
}

 

Recomendación:

Debemos tener la precaución de usar adecuadamente las preferencias. El objetivo de las mismas es tal lo que dice su nombre, guardar preferencias, clave + valor.

Este es un ejemplo para casos particulares.

Si lo que necesitamos es guardar objetos del negocio deberías utilizar otro medio de persistencia. Sqlite cumple ese objetivo.

Hi! If you find my posts helpful, please support me by inviting me for a coffee :)

Ver también