Skip to content

Instantly share code, notes, and snippets.

Created January 17, 2015 09:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/2f9aa35a1a3cf0bcf0d5 to your computer and use it in GitHub Desktop.
Save anonymous/2f9aa35a1a3cf0bcf0d5 to your computer and use it in GitHub Desktop.
SharedPrefsSavable
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.gson.Gson;
/** A base class which will allow your class to be Json-serialized to a private SharedPreferences storage.
*/
public class SharedPrefsSavable {
/** True if the object was created from scratch this session */
private transient boolean mIsNew;
/** Loads and deserializes user preferences of type "type" */
public static <T extends SharedPrefsSavable> T load(Class type, Context context) {
T userData = null;
try {
String stringData = loadRaw(type, context);
if (stringData != null) {
userData = (T) new Gson().fromJson(stringData, type);
}
}
catch (Exception ex)
{
Log.e("SharedPrefsSavable", ex.getMessage());
}
if (userData == null) {
try {
userData = (T) type.newInstance();
((SharedPrefsSavable) userData).mIsNew = true;
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
return userData;
}
public void save(Context context) {
String prefsKey = getPrefsKey(context);
SharedPreferences prefs = context.getSharedPreferences(prefsKey, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
String asString = new Gson().toJson(this);
String objectKey = getPreferencesId();
editor.putString(objectKey, asString);
editor.commit();
}
private static String getPrefsKey(Context context) {
return context.getPackageName();
}
private static String getPreferencesId(Class<? extends SharedPrefsSavable> type) {
return type.getName();
}
public String getPreferencesId() {
return SharedPrefsSavable.getPreferencesId(this.getClass());
}
/** Fetches the stored user preferences from local storage and returns raw string data. */
public static String loadRaw(Class type, Context context) {
String prefsKey = getPrefsKey(context);
SharedPreferences prefs = context.getSharedPreferences(prefsKey, Context.MODE_PRIVATE);
String key = getPreferencesId(type);
String stringData = prefs.getString(key, null);
return stringData;
}
/** True if the object was created from scratch this session */
public boolean isNew() {
return mIsNew;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment