Skip to content
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.

Usage

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();
    }
}

Details

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.

Hints

  1. 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 from getXXX methods.
  2. If you want to have a different (not 0 or null) value returned as default, simply assign this value to one of your fields. Before first call to setXXX or after a call to removeXXX, your field's value will be returned from getXXX.
  3. Curious about how generated code looks like? Take a look at files starting with Preferences in before and after.

Works well with

Nothing. Awesome by itself.

Clone this wiki locally