Skip to content
David Kunzler edited this page Jul 14, 2020 · 3 revisions

Defaults

Each preference has a default value in case the preference is not present when calling the getter. Esperandro provides implicit defaults when no other default is defined. These are:

Type Default value
int -1
long -1l
float -1.0f
char 0
boolean false
String "" (empty String)
Set<String> null

Defining default Values

Static defaults can be defined at compile time via the @Default annotation. For each basic type of preference (except Set<String>) exists a possible parameter in this annotation. The parameter is named ofInt, ofLong, ofString, ... If this annotation is present on the getter the defined value will be returned when no value was already saved for this preference.

@SharedPreferences
interface MyPreferences {
    @Default(ofString = "Hello World")
    String getMyPreference();
    void setMyPreference(String myPreference);
}

Complex defaults

Since annotations have the restriction to only allow final static values there is an additional option. The ofStatement definition will use the defined string value exactly as is when calling the underlying SharedPreference. That means that code that is put into this statement will get executed at runtime. Be aware that every class reference used here needs to be fully qualified since no additional imports are added to the generated file.

@SharedPreferences
interface MyPreferences {
    @Default(ofStatement = "de.devland.esperandro.Example.calculateDefaultValue()")
    String getMyPreference();
    void setMyPreference(String myPreference);
}

The above example would call the method calculateDefaultValue of the class Example to determine which default value will be used when retrieving this preference.

Runtime defaults

In some cases a non-static default is desired. For example if the default value is dependent of the current state of the App. For this case there is the possibility to define a method with an explicit default parameter that will be used.

The name of the method is the same as for the normal getter. The method needs to have one parameter which represents the desired default.

@SharedPreferences
interface MyPreferences {
    String getMyPreference(String defaultValue);
    void setMyPreference(String myPreference);
}

The above example shows the definition of such a method. A call to this method could look like:

MyPreferences instance = Esperandro.getPreferences(MyPreferences.class, context)
String value = instance.getMyPreference(editText.getText());

In this example the required default is dependent of the value in an EditText.

Clone this wiki locally