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

Usage

To get started with esperandro add the following artifacts to the dependencies section of your build.gradle:

implementation 'de.devland.esperandro:esperandro-api:<insert version>'
annotationProcessor 'de.devland.esperandro:esperandro-preference-gen:<insert version>'

Define a simple Preference Interface

Any interface annotated with @SharedPreferences will be used for generation. The annotation can have a name and a mode which act exactly like name and mode in standard android SharedPreferences. Without a name the app's default preferences are assumed.

@SharedPreferences
public interface DefaultPreferences {}

Adding preferences

A preference in esperandro is represented by a set of two methods. A getter and a setter. A getter has no parameters and uses the desired type as return type. Opposed to that a setter uses the desired type as the single parameter to a void-returning method. The method names of a preference adhere to the Java default accessor syntax hence using get/set prefixes at the methods.

Adding a preference with the name myPreference of type string will result in the following interface definition:

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

Esperandro will now generate an implementation for this interface.

Obtain instance

To get an instance of the interface a static call to the class Esperandro is made

MyPreferences instance = Esperandro.getPreferences(MyPreferences.class, context)

where context can be either and application or an activity context.

Accessing values

This instance can now be used to load and store the defined preference.

String value = instance.getMyPreference();
...
value = "esperandro is great";
instance.setMyPreference(value);

Commit and Apply

Esperandro supports both, commit and apply operations. (Read more on the differences here)

To make a setter for a preference value use commit instead of apply simply change the return type in the interface to boolean.

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

Now the boolean return value of the commit call is propagated and can be used for error-handling.

Clone this wiki locally