EasyPrefs Documentation

repository·master·Indexed 19 days ago

https://github.com/pixplicity/easyprefs

A lightweight wrapper for Android's SharedPreferences that reduces boilerplate for saving and retrieving primitive data types. It features a Builder for initialization and provides ordered set support via LinkedHashSet to preserve insertion order.

Tokens
639
Snippets
4
Records
4
Agent score
15%

What's inside EasyPrefs

  1. Initialize EasyPrefs in your Application class

    master

    To use EasyPrefs, you must initialize it within the onCreate method of your Application class using the Prefs.Builder. This sets up the global shared preferences instance.

    class PrefsApplication : Application() {
    
        override fun onCreate() {
            super.onCreate()
            // Initialize the Prefs class
            Prefs.Builder()
                    .setContext(this)
                    .setMode(ContextWrapper.MODE_PRIVATE)
                    .setPrefsName(packageName)
                    .setUseDefaultSharedPreference(true)
                    .build()
        }
    
    }
  2. Save and retrieve values with EasyPrefs

    master

    Once initialized, you can use static methods to save and retrieve primitive types without manual null checks or contains() calls. If a key does not exist, the retrieval methods return the provided default value.

    // Saving values
    Prefs.putString("key", "string_value");
    Prefs.putLong("key", 123L);
    Prefs.putBoolean("key", true);
    
    // Retrieving values
    String data = Prefs.getString("key", "default_value");
  3. Use ordered sets to preserve insertion order

    master

    Standard Android getStringSet does not guarantee the order of strings. EasyPrefs provides putOrderedStringSet and getOrderedStringSet which use LinkedHashSet internally to ensure a predictable iteration order and provide compatibility for pre-Honeycomb devices.

    // Saving an ordered set
    Prefs.putOrderedStringSet("my_set_key", mySet);
    
    // Retrieving an ordered set
    Set<String> mySet = Prefs.getOrderedStringSet("my_set_key", new HashSet<String>());