How to use sharedpreferences as class

1

I would like to know how I get to receive a data and assign it in a SharedPreferences class so that I can use this value whenever I need it. Below is my code and where I need it to change.

This is a list of drives I get:

ltsunidades.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView adapter, View view, int posicao, long id) {

        Object obj = adapter.getItemAtPosition(posicao);
        String filial = "" + obj;

        eu preciso armarzenar essa string filial   nesse sharedpreferences 
        UnidadePreferida.setfilial(c,filial.toString().trim());

        Intent it = new Intent(getBaseContext(), Empresa.class);
        it.putExtra("Filial", filial);
        startActivity(it);


        /*SharedPreferences sharedPref2 = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref2.edit();
        editor.putString("Filial", filial);
        editor.commit();*/
        //Toast.makeText(getApplicationContext(), "" + filial, Toast.LENGTH_SHORT).show();
    }
});

And here is the class I want to save this value to SharedPreferences to use when I want:

public class UnidadePreferida {

    public static SharedPreferences getSharedPreferences(Context context) {
        return context.getSharedPreferences("energy", Context.MODE_PRIVATE);
    }

    public static void setfilial(Context context, String filial) {
        SharedPreferences sharedPref = getSharedPreferences(context);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("Filial", filial);
        editor.commit();
    }

    public static String getfilial(Context context) {
        SharedPreferences sharedPref = getSharedPreferences(context);
        return sharedPref.getString("Filial", "");
    }
}
    
asked by anonymous 11.04.2016 / 15:11

2 answers

3

My solution proposal for your UnidadePreferida class is:

import android.content.SharedPreferences;
puclic class UnidadePreferida {

    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;

    public UnidadePreferida(SharedPreferences preferences){
       this.preferences = preferences;
       this.editor = this.preferences.edit();
    }

    // Método genérico serve para salvar qualquer tipo de preferencia String
    // não só sua filial
    public void savePreferenceString(String key, String value){
       this.editor.putString(key,value);
       this.editor.commit();
    }

    public String getPreferenceString(String key){
       return this.preferences.getString(key,"");
    }

}

Now in your Activity use as follows:

ltsunidades.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView adapter, View view, int posicao, long id) {

    Object obj = adapter.getItemAtPosition(posicao);
    String filial = "" + obj;

    private static final String PREFS_NAME = "NamePreference";
    UnidadePreferida up = new UnidadePreferida(getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE));
    up.savePreferenceString("Filial",filial.toString().trim());

    Intent it = new Intent(getBaseContext(), Empresa.class);
    it.putExtra("Filial", filial);
    startActivity(it);
}

});

    
11.04.2016 / 16:27
3

In order to facilitate this leitura/gravação , I created a Generic class to store Classes in SharedPreferences :

The class below is an example of Usage:

Class Model:

  

SharedPreferencesModel.java

import android.content.Context;
import android.content.SharedPreferences;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Classe controla os Objetos que serão salvos/lidos no SharedPreferences
 */
public class SharedPreferencesModel<T> {

    /**
     * Carrega o Objeto relacionada a Classe solicitada como parametro
     */
    public T load(final Class<?> _class, final Context mContext){
        if(null == _class || null == mContext) return null;

        final String name = _class.getSimpleName().toUpperCase();
        final SharedPreferences prefs = mContext.getSharedPreferences(name, Context.MODE_PRIVATE);
        final Method[] methods = _class.getDeclaredMethods();
        final List<Method> sets = new ArrayList<>(0);
        for(final Method method : methods)
        {
            if("set".equals(method.getName().substring(0, 3)))
            {
                sets.add(method);
            }
        }

        try {
            T obj = (T)_class.newInstance();

            for(final Method method : sets){
                final String getName = method.getName();
                final String paramName = getName.substring(3, getName.length()).toUpperCase();
                final String type  = method.getParameterTypes()[0].getSimpleName();

                if("String".equals(type))
                {
                    final String value = prefs.getString(paramName, "");
                    method.invoke(obj, value);
                }
                else if("Integer".equals(type))
                {
                    final Integer value = prefs.getInt(paramName, 0);
                    method.invoke(obj, value);
                }
                else if("Long".equals(type))
                {
                    final Long value = prefs.getLong(paramName, 0);
                    method.invoke(obj, value);
                }
                else if("Float".equals(type) )
                {
                    final Float value = prefs.getFloat(paramName, 0);
                    method.invoke(obj, value);
                }
                else if("Double".equals(type))
                {
                    final String value = prefs.getString(paramName, "0");
                    method.invoke(obj, Double.valueOf(value));
                }
                else if("Boolean".equals(type)){
                    Boolean value = prefs.getBoolean(paramName, false);
                    method.invoke(obj, value);
                }
            }

            return obj;

        } catch (final Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * Salva as informações do objeto no SharedPreferences.
     */
    public void save(final T object, final Context mContext){
        if(null == object || null == mContext) return;
        final String name = object.getClass().getSimpleName().toUpperCase();
        final SharedPreferences prefs = mContext.getSharedPreferences(name, Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = prefs.edit();

        final Method[] methods = object.getClass().getDeclaredMethods();
        final List<Method> gets = new ArrayList<>(0);
        for(final Method method : methods)
        {
            if("get".equals(method.getName().substring(0, 3)))
            {
                gets.add(method);
            }
        }
        for(final Method method : gets)
        {
            final String getName = method.getName();
            final String paramName = getName.substring(3, getName.length()).toUpperCase();
            try {
                final Object param = method.invoke(object);
                if(null == param)
                {
                    continue;
                }
                final String type = param.getClass().getSimpleName();

                if("String".equals(type))
                {
                    editor.putString(paramName, String.class.cast(param));
                }
                else if("Integer".equals(type))
                {
                    editor.putInt(paramName, Integer.class.cast(param));
                }
                else if("Long".equals(type))
                {
                    editor.putLong(paramName, Long.class.cast(param));
                }
                else if("Float".equals(type) )
                {
                    editor.putFloat(paramName, Float.class.cast(param));
                }
                else if("Double".equals(type))
                {
                    editor.putString(paramName, String.valueOf(param)); /// guardamos o Double como String
                }
                else if("Boolean".equals(type)){
                    editor.putBoolean(paramName, Boolean.class.cast(param));
                }

            } catch (final Exception e) {
                e.printStackTrace();
            }
        }
        editor.apply();
    }

}
  

Example Usage

Example class to store:

UserData.java

public class DadosUsuario {

    private String nome;
    private Long id;
    private String mail;
    private Float saldoAtual;

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }

    public Float getSaldoAtual() {
        return saldoAtual;
    }

    public void setSaldoAtual(Float saldoAtual) {
        this.saldoAtual = saldoAtual;
    }
}
  

How to save / read

  //  Informamos qual classe vamos trabalhar...
    SharedPreferencesModel<DadosUsuario> model = new SharedPreferencesModel<>();

    // Modelo de dados
    DadosUsuario dadosUsuario = new DadosUsuario();
    dadosUsuario.setId(123L);
    dadosUsuario.setMail("[email protected]");
    dadosUsuario.setNome("Nome");
    dadosUsuario.setSaldoAtual(12.3f);

    // para salvar, passamos a classe o o Context
    model.save(dadosUsuario, getApplicationContext());

    // Para carregar, passamos o .class e o Context
    DadosUsuario persistido = model.load(DadosUsuario.class, getApplicationContext());
    
11.04.2016 / 17:33