In order to facilitate this leitura/gravação
, I created a Generic class to store Classes in SharedPreferences
:
Below is the class and an example of Usage:
Model Class:
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 of Use
Example class we will store:
Dadosusuario.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());
thanks but now I need to use this preferred Unit class here url = url.replace("par1", Drivepreferred.getfilial(this)); Log. i("URL", "" + url); how it would look now pq gave error in getfilial
– Tiago
to give a
get
you’ll wear it like thisup.getPreferenceString("Filial");
– Igor Mello