android - Store a collection of objects in SharedPreferences -


i working on developing utility class storing data in sharedpreferences. till now, able make generic function store , retrieve string, int , boolean. there generic way store , retrieve collection of objects?

there no direct way 2 indirect ways:

1. use gson.

public static boolean saveobjecttoprefs(string prefkey, object object, context context) {     sharedpreferences.editor editor = getsharedpreferences(context).edit();     try {         gson gson = new gson();         string json = gson.tojson(object);         editor.putstring(prefkey, json);         editor.apply();         return true;     } catch (exception e) {          e.printstacktrace();          return false;     } } 

the generic here should implement serializable interface.

to retrieve object create method this:

public static <t> t getobjectfromprefs(string prefkey, class<t> type, context context) {     string json = getsharedpreferences(context).getstring(prefkey, null);     if (json != null) {         try {             gson gson = new gson();             t result = gson.fromjson(json, type);             return result;         } catch (exception e) {             e.printstacktrace();         }     }     return null; } 

and can call method collections:

prefutils.getobjectfromprefsbytype(pref_key_users, new typetoken<arraylist<user>>() {     }.gettype(), context); 

for normal objects can do:

prefutils.getobjectfromprefsbytype(pref_key_user, user.class, context); 

2. write custom serializer , deserializer

i prefer method don't have include library it.

here custom serializer/deserializer implemetation:

public class objectserializer {   public static string serialize(serializable obj){     if (obj == null) return "";     try {         bytearrayoutputstream serialobj = new bytearrayoutputstream();         objectoutputstream objstream = new objectoutputstream(serialobj);         objstream.writeobject(obj);         objstream.close();         return encodebytes(serialobj.tobytearray());      } catch (exception e) {         e.printstacktrace();         return null;     }  }  public static object deserialize(string str)  {     if (str == null || str.length() == 0) return null;     try {         bytearrayinputstream serialobj = new bytearrayinputstream(decodebytes(str));         objectinputstream objstream = new objectinputstream(serialobj);         return objstream.readobject();     } catch (exception e) {         e.printstacktrace();         return null;     } }  public static string encodebytes(byte[] bytes) {     stringbuilder strbuf = new stringbuilder();     (byte b: bytes) {         strbuf.append((char) (((b >> 4) & 0xf) + ((int) 'a')));         strbuf.append((char) (((b) & 0xf) + ((int) 'a')));     }     return strbuf.tostring(); }  public static byte[] decodebytes(string str) {     byte[] bytes = new byte[str.length() / 2];     (int = 0; < str.length(); i+=2) {         char c = str.charat(i);         bytes[i/2] = (byte) ((c - 'a') << 4);         c = str.charat(i+1);         bytes[i/2] += (c - 'a');     }     return bytes;     } } 

now, inside prefutils.java can have method like:

public static void saveuser(context context, user user) {     getsharedpreferences(context)                         .edit()                         .putstring(pref_key_user, objectserializer.serialize(user))                         .apply(); } 

to retrieve object can use following method:

public static user getuser(context context) {     string serializeduser = getsharedpreferences(context).getstring(pref_key_user, "");     return ((user) objectserializer.deserialize(serializeduser)); } 

again user class has serializable. also, don't forgot explicit casting objectserializer.deserialize(string str) method returns object of type object , not class serialized. also, take care of null values.


Comments

Popular posts from this blog

gridview - Yii2 DataPorivider $totalSum for a column -

java - Suppress Jboss version details from HTTP error response -

Sass watch command compiles .scss files before full sftp upload -