MobileUI LogoMobileUI
/

🔌 Preferences

Store app-related preferences in a simple key-value store


The Preferences Plugin PURPLE gives you a simple interface for storing and retrieving preferences in a platform-agnostic manner. Under the hood, the preferences plugin uses uses SharedPreferences on Android and NSUserDefaults on iOS.

Plugin Infos
Dependency"io.nevernull:mobileui-plugin-preferences"
Api Docsio.nevernull.mobileui.preferences
Main Interfaceio.nevernull.mobileui.preferences.Preferences

Example Usage

Here is how to store, retrieve, update and delete preferences.

PreferencesController.java
@Prototype
public class PreferencesController implements LifecycleAware {
    
    @Inject
    Preferences preferences;

    public static final String LAST_START = "lastStart";
    public static final String LAST_TIME_STAMP = "lastTimeStamp";
    public static final String LAST_BOOLEAN = "lastBoolean";
    public static final String STRING_SET = "stringSet";

    public String lastStart = "not set";
    public long lastTimeStamp = -1l;
    public boolean lastBoolean = false;
    public Set<String> stringSet;

    @Override
    public void onStart(Object lifeCycleSource) {
        // Load the preferences when this controller starts
        loadFromPreferences();
    }

    public void onUpdatePreferencesClicked() {
        // Update preferences when the user has clicked a button
        preferences.set(LAST_START, new Date().toString());
        preferences.set(LAST_TIME_STAMP, System.currentTimeMillis());
        preferences.set(LAST_BOOLEAN, true);
        preferences.set(STRING_SET, new HashSet<>(Arrays.asList("Daniel", "Ansgar", "Henrik")));
        loadFromPreferences();
    }

    public void onClearClicked() {
        // Delete preferences
        preferences.clear();
        loadFromPreferences();
    }

    private void loadFromPreferences() {
        // Load the values from the preferences
        stringSet = preferences.getStringSet(STRING_SET, Collections.emptySet());
        lastStart = preferences.getString(LAST_START, "");
        lastTimeStamp = preferences.getLong(LAST_TIME_STAMP, 0l);
        lastBoolean = preferences.getBoolean(LAST_BOOLEAN, false);
        MobileUI.firePropertyChanged(this, LAST_START, LAST_TIME_STAMP, LAST_BOOLEAN, STRING_SET);
    }
}