Skip to content

Instantly share code, notes, and snippets.

@timfreiheit
Last active February 26, 2016 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timfreiheit/ab49102611f24dc45ecf to your computer and use it in GitHub Desktop.
Save timfreiheit/ab49102611f24dc45ecf to your computer and use it in GitHub Desktop.
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import com.f2prateek.rx.preferences.Preference;
/**
* Caches an result in memory to avoid fetching and parsing it for every call
* IMPORTANT: the value will not update automatically if you change the preferences in another way than using
* {@link Preference#set(Object)}
* Created by timfreiheit on 05.12.15.
*/
public class CachingPrefsAdapter<T> implements Preference.Adapter<T> {
Preference.Adapter<T> adapter;
T t;
public CachingPrefsAdapter(Preference.Adapter<T> adapter){
this.adapter = adapter;
}
@Override
public T get(@NonNull String key, @NonNull SharedPreferences preferences) {
if (t == null) {
t = adapter.get(key, preferences);
}
return t;
}
@Override
public void set(@NonNull String key, @NonNull T value, @NonNull SharedPreferences.Editor editor) {
t = value;
adapter.set(key, value, editor);
}
}
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import com.f2prateek.rx.preferences.Preference;
import com.google.gson.Gson;
/**
* Preferences Adapter to use gson for serializing
* Created by timfreiheit on 05.12.15.
*/
public class GsonPrefsAdapter<T> implements Preference.Adapter<T> {
final Gson gson;
private Class<T> clazz;
private T defaultValue;
public GsonPrefsAdapter(Class<T> clazz){
this(new Gson(), clazz);
}
public GsonPrefsAdapter(Gson gson, Class<T> clazz){
this(new Gson(), clazz, null);
}
public GsonPrefsAdapter(Gson gson, Class<T> clazz, T defaultValue){
this.gson = gson;
this.clazz = clazz;
this.defaultValue = defaultValue;
}
@Override
public T get(@NonNull String key, @NonNull SharedPreferences preferences) {
String json = preferences.getString(key, null);
if (json == null) {
return defaultValue;
}
return gson.fromJson(json, clazz);
}
@Override
public void set(@NonNull String key, @NonNull T value, @NonNull SharedPreferences.Editor editor) {
editor.putString(key, gson.toJson(value));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment