forked from projectlombok/lombok
-
Notifications
You must be signed in to change notification settings - Fork 11
Preferences
Maciej Górski edited this page Jun 6, 2014
·
4 revisions
Preferences
annotation is used to create a very nice, strongly typed API for working with android.content.SharedPreferences
.
Now you can write
import hrisey.Preferences;
@Preferences
public final class MyPrefs {
private float myFloat;
private int myInt = 1000;
}
instead of
import android.content.SharedPreferences;
public final class MyPrefs {
private static final String MY_FLOAT = "myFloat";
private static final String MY_INT = "myInt";
private final SharedPreferences prefs;
public MyPrefs(SharedPreferences prefs) {
this.prefs = prefs;
}
public float getMyFloat() {
return this.prefs.getFloat(MY_FLOAT, 0.0f);
}
public void setMyFloat(float myFloat) {
this.prefs.edit().putFloat(MY_FLOAT, myFloat).apply();
}
public boolean containsMyFloat() {
return this.prefs.contains(MY_FLOAT);
}
public void removeMyFloat() {
this.prefs.edit().remove(MY_FLOAT).apply();
}
public int getMyInt() {
return this.prefs.getInt(MY_INT, 1000);
}
public void setMyInt(int myInt) {
this.prefs.edit().putInt(MY_INT, myInt).apply();
}
public boolean containsMyInt() {
return this.prefs.contains(MY_INT);
}
public void removeMyInt() {
this.prefs.edit().remove(MY_INT).apply();
}
}
SharedPreferences
supports only a very limited number of types: bool
, float
, int
, long
and String
.
double
is supported by conversion to long
with a help of Double.doubleToLongBits
.
All other types are serialized to String
using Google Gson library. If you declare one or more of your fields of a type not directly supported, your preferences class will have generated constructor with additional parameter of class com.google.gson.Gson
.
- Make sure to pass immutable objects (e.g. annotated with @Value) to
setXXX
methods of annotated class. In future release objects might be directly cached to avoid repeated deserialization and the same object will be returned fromgetXXX
methods. - If you want to have a different (not
0
ornull
) value returned as default, simply assign this value to one of your fields. Before first call tosetXXX
or after a call toremoveXXX
, your field's value will be returned fromgetXXX
. - Curious about how generated code looks like? Take a look at files starting with Preferences in before and after.
Nothing. Awesome by itself.