[Library] StoreBox, an open-source Android library for streamlining SharedPreferences topic

SOCIALIZE IT ⇨


When getting a value from any preferences, whether private Activity or default shared preferences, you would normally have to get a reference to a SharedPreferences instance, for example using


Code:


SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(someContext);


Only after that we can start getting the values out, such as


Code:


String myValue = prefs.getString("someKey", "someDefaultValue");


This can get reasonably tedious if the preferences need to be accessed from multiple places, and the API always requires us to pass a key and a default value. This can get error prone quickly, and increases with the amount of keys and default values that need to be used. Putting commonly accessed preferences behind a wrapper is a reasonable solution, but still requires some boilerplate code.

What if however we could define an interface like


Code:


public interface MyPreferences {

    @KeyByString("someKey")
    String getSomeValue();
}



for everyone to use in order to save and get values?

With StoreBox that becomes reality. Given the above interface definition you can easily create an instance of the interface using


Code:


MyPeferences prefs = StoreBox.create(context, MyPeferences.class);


and you will be able to retrieve the value just by calling the defined method


Code:


String myValue = prefs.getSomeValue();


You can read more about the project here, including details on how it can be used and added to a project.

Let me know what you think and whether you find it useful. Thanks!




xda-developers


0 commentaires:

Enregistrer un commentaire