Need help with StoreBox?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

209 Stars 16 Forks Apache License 2.0 96 Commits 11 Opened issues


Android library for streamlining SharedPreferences

Services available


Need anything else?

Contributors list

# 370,727
88 commits
# 80,238
1 commit
# 1,479
1 commit


Android library for streamlining SharedPreferences.
Build Status Codacy Badge Download Android Arsenal



StoreBox is an annotation-based library for interacting with Android's SharedPreferences, with the aim take out the the how and where parts of retrieving/storing values and instead focus on the more important what part.

Normally when retrieving or storing values we need to know two pieces of information during each call: the key and the type.

String username = preferences.getString("key_username", null);
preferences.edit().putString("key_date_of_birth", "30/09/2004").apply(); // should this be a String or a long?

With StoreBox the operations above can be changed into pre-defined methods with improved semantics. ```Java // definition public interface MyPreferences {

String getUsername();

@KeyByString("key_date_of_birth") void setDateOfBirth(String value);


// usage MyPreferences preferences = StoreBox.create(context, MyPreferences.class); String username = preferences.getUsername(); preferences.setDateOfBirth("30/09/2004"); ``` The caller now doesn't need to worry about the key, neither about what type the values are stored under. The only important part that needs to be taken into consideration is what is done with the values, whether that is storing them for later, showing them to the user in the UI, or just changing application behaviour.

Read on to find out more details about how StoreBox can be used and how it can be added to an Android project.

Adding to a project

StoreBox can be used in Android projects using minimum SDK version 10 and newer (Android 2.3+).


v1.4.0 JAR
v1.4.0 JavaDoc JAR


compile ''


Defining an interface and bringing it to life

Simply create a new interface class in your IDE or a text editor, give it an access modifier which suits its use, and name it as appropriate. ```Java public interface MyPreferences {


Now you're ready to use [`StoreBox.create()`]( to obtain an instance.
Java MyPreferences instance = StoreBox.create(context, MyPreferences.class); ```

Adding get and set methods

If you would like to add a getter just add a method to the interface which returns a value and make sure to annotate it using

. ```Java @KeyByString("key_nickname") String getNickname();

@KeyByResource(R.string.key_notifications) boolean shouldShowNotifications(); ```

Adding a setter is just as easy. The same annotations will need to be used as for getter methods, but now our method will return nothing and will have to provide a parameter for supplying the value that should be saved. ```Java @KeyByString("key_nickname") void setNickname(String value)

@KeyByResource(R.string.key_notifications) void setNotifications(boolean value) ```

Specifying defaults for get methods

This can be achieved in two ways, through an argument or by using an annotation.

For the first option the following will work.

String getPhoneNumber(String defValue);
And using an annotation referencing a default found in the XML resources.
String getPhoneNumber();

For some types, such as

, which cannot be added to the resources an integer resource may be used instead.
long getRefreshInterval();

Storing and retrieving custom types

Saving custom types, which are not understood by Android's SharedPreferences, can be supported through the use of type adapters. A type adapter implementation can be provided by extending from one of the following classes: *

for storing as a

for storing as a
and so on... *
(only supported on API11 and newer)

Telling StoreBox which type adapter should be used can be done by adding the

annotation to the get and set methods. ```Java @KeyByString("key_region") @TypeAdapter(RegionTypeAdapter.class) Region getRegion();

@KeyByString("key_region") @TypeAdapter(RegionTypeAdapter.class) void setRegion(Region value); ```

Which type adapter needs to be extended depends on the use case. Take a look at the

, and
for some examples. It is worth noting that in the last example Gson is being used for serialising the type, as opposed to writing a custom implementation. Gson is not used internally by StoreBox, as such if you wish to use Gson for a type adapter you will need to add it to your project as a dependency.

The following types will work out of the box, so type adapters don't need to be provided for them: *


Disclaimer: APIs around type adapters may change in the future, as I will keep looking for a less verbose way of achieving the same goal without requiring the use of Gson.

Opening different types of preferences

In all of the examples so far details about what preferences are opened and how have been omitted.

Without any annotation the default shared preferences will be used, but the

annotation can be added to the interface definition for explicitness. Likewise,
can be used to respectively open preferences private to an activity or to open preferences using a file name.

The mode with which the preferences should be opened can also be specified, although this option is not supported by all the types. ```Java @ActivityPreferences(mode = PreferencesMode.MULTI_PROCESS) public interface WelcomeActivityPreferences {

// method definitions here...

} ```


Remove and clear methods

In order to remove a value stored in the preferences under a key a method to perform the removal can be annotated with the

annotation. The key can be supplied in two ways;

The key can be provided thorough an argument in the method, using either a

or an
in the case of the key being specified in an XML resource. ```java public interface RemoveMethodExample {
void remove(String key);

@RemoveMethod void remove(int keyRes);


// usage preferences.remove("keyusername"); preferences.remove(R.string.keypassword); ```

Or a value-specific remove method can be defined with the help of the

annotations. ```java public interface RemoveMethodExample {

void removeUsername();

@KeyByResource(R.string.key_password) @RemoveMethod void removePassword();


// usage preferences.removeUsername(); preferences.removePassword(); ```

Clearing all values stored in the preferences can be done by annotating a method with the

annotation. ```java public interface ClearMethodExample {

void clear();


// usage preferences.clear(); ```

Change listeners

Callbacks can be received when a preference value changes through the use of the

interface. The listeners need to be parametrised with the type which is used for the value whose changes we would like to listen for. For example, if we would like to listen to changes to the password (from previous examples) then we could define the listener as

OnPreferenceValueChangedListener listener = new OnPreferenceValueChangedListener() {
    public void onChanged(String newValue) {
        // do something with newValue
To register this listener a method for registering the listener would need to be defined using the
annotation in the interface which gets passed to
. Likewise, for unregistering a listener the method needs to be annotated with
instead. The
annotation also needs to be used to specify which value we are interested in. ```Java public interface ChangeListenerExample {
void registerPasswordListener(OnPreferenceValueChangedListener listener);

@KeyByString("key_password") @UnregisterChangeListenerMethod void unregisterPasswordListener(OnPreferenceValueChangedListener listener);

} ``

If you would like to listen for changes to a custom type then the [
@TypeAdapter`](storebox-lib/src/main/java/net/orange_box/storebox/annotations/method/ annotation will need to be added to the method in order to tell StoreBox how the value should be adapted when retrieving it from the preferences.

More than one listener can be registered and unregistered at a time by changing the method definitions in the interface to use variable arguments.

// annotations omitted
void registerPasswordListeners(OnPreferenceValueChangedListener... listeners);

Caution: StoreBox does not store strong references to the listeners. A strong reference must be kept to the listener for as long as the listener will be required, otherwise it will be susceptible to garbage collection.

Chaining calls

With Android's

class it is possible to keep chaining put methods as each returns back the

instance. StoreBox allows the same functionality. All that needs to be done is to change the set/remove method definitions to either return interface type itself or
. ```Java public interface ChainingExample {
ChainingExample setUsername(String value);

@KeyByString("key_password") ChainingExample setPassword(String value);

@KeyByString("key_country") ChainingExample removeCountry();


And calls can be chained as
Java preferences.setUsername("Joe").setPassword("jOe").removeCountry(); ```

Forwarding calls

If you would like to access methods from the

, you can do that by extending your interface from either of the above (or even both). ```Java public interface ForwardingExample extends SharedPreferences, SharedPreferences.Editor {

// method definitions here


And the methods from either of the extended interfaces will be callable.
Java String username = preferences.getString("keyusername", ""); preferences.putString("keyusername", "Joe").apply(); ```

Save modes

Changes to preferences can normally be saved on Android either through

. Which method gets used can be customised in StoreBox through the use of the

Unlike any of the previous annotations

can be used to annotate both the interface as well as individual set/remove methods, however an annotation at method-level will take precedence over an interface annotation. ```Java @SaveOption(SaveMode.APPLY) public interface SaveModeExample { // key annotations omitted
void setUsername(String value); // will save using apply()

@SaveOption(SaveMode.COMMIT) void setPassword(String value); // will save using commit()

@SaveOption(SaveMode.COMMIT) void removeUsername(); // will persist using commit()

} ```


StoreBox supports versioning of preferences through the use of the

interface-level annotation, in a similar fashion to Android's
. This functionality may be required in the case when the schema of the preferences needs to be changed, such as when a key or type of a preference changes, an enum constant is added/renamed/removed, or a class which is being stored in the preferences changes internally. The

annotation needs to be added to the interface which will be used with

By default, without the

annotation, the version used is assumed to be
. The first time a change is required the
for the annotation should be set to
, with the value being incremented for any subsequent changes. To provide the logic for handling version upgrades a
class extending from
needs to be specified.
@PreferencesVersion(version = 1, handler = MyPreferencesVersionHandler.class)
public interface MyPreferences {

// method definitions here


public class MyPreferencesVersionHandler extends PreferencesVersionHandler {

protected void onUpgrade(
        SharedPreferences prefs,
        SharedPreferences.Editor editor,
        int oldVersion,
        int newVersion) {

    // logic for handling upgrades


For an initial upgrade from

method will be called with
oldVersion = 0
newVersion = 1
. If the version of the preferences would be updated to
, then the handler would be called with
oldVersion = 1
newVersion = 2
. If however an application update using version
was skipped, then
would be called with
oldVersion = 0
newVersion = 2
, which means that handling the intermediate upgrade between versions
would be required. Calling
on the
is not required after changes are made, as StoreBox will take care of this when saving the new version value into the preferences. Take a look here for an example of how upgrades could be handled.

The versions are also independent of each other, and apply only to specific preference files. For example, you could have a shared preferences with version X, activity A preferences with version Y, and activity B preferences with version Z. Or none at all, if versioning is not needed.

Obtaining a more customised instance at run-time

As previously described you can build an instance of your interface using

, however if you'd like to override at run-time any annotations you can use
and apply different options.
MyPreferences preferences =
        new StoreBox.Builder(context, MyPreferences.class)


Given the minimum amount of details provided to the interface and method definitions through the use of StoreBox's annotations, the following defaults will get used: * Preferences type: Default shared preferences * Preferences mode: Private * Save mode: Apply * Default value mode: Empty


If you are using ProGuard add the following lines to your configuration. ``` -dontwarn net.jodah.typetools.TypeResolver -keep class net.orange_box.storebox.** { ; } -keepattributes *Annotation,Exceptions,InnerClasses,Signature

## Contributing ##
Any contributions thorough pull requests as well as raised issues (bugs are rated just as highly as features!) will be welcome and highly appreciated.

If you would like to submit a pull request please make sure to do so against the develop branch, and please follow a similar code style to the one used in the existing code base. Running the tests before and after any changes is highly recommended, just as is adding new test cases.



Copyright 2015 Martin Bella

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ```

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.