Last active
August 6, 2017 16:32
-
-
Save omaraflak/a5e3ad698a8b83a2f75ffbdb847e5b0a to your computer and use it in GitHub Desktop.
Small wrapper for shared preferences.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// build.gradle | |
// implementation 'com.google.code.gson:gson:2.8.1' | |
public class ObjectSaver { | |
private static SharedPreferences sharedPreferences; | |
private static Resources resources; | |
private static Gson gson; | |
public static void init(Context context) { | |
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); | |
resources = context.getResources(); | |
gson = new Gson(); | |
} | |
public static void put(String key, Object o){ | |
sharedPreferences.edit() | |
.putString(key, gson.toJson(o)) | |
.apply(); | |
} | |
public static void put(int resKey, Object o){ | |
put(resources.getString(resKey), o); | |
} | |
public static <T> T get(String key, Class<T> type){ | |
return gson.fromJson(sharedPreferences.getString(key, null), type); | |
} | |
public static <T> T get(int resKey, Class<T> type){ | |
return get(resources.getString(resKey), type); | |
} | |
} | |
// Initialize one time | |
public class MyApp extends Application { | |
@Override | |
public void onCreate() { | |
super.onCreate(); | |
ObjectSaver.init(this); | |
} | |
} | |
// Then use whenever you want | |
public void somewhere(){ | |
ObjectSaver.put("object", new User("Omar", 19)); | |
User user = ObjectSaver.get("object", User.class); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment