StoreBox
Android library for streamlining SharedPreferences
Install / Use
/learn @martino2k6/StoreBoxREADME
StoreBox
Android library for streamlining SharedPreferences.
Contents
- Overview
- Adding to a project
- Interface and creation
- Get and set methods
- Defaults for get methods
- Custom types
- Preference types
- Advanced
- Remove and clear methods
- Change listeners
- Chaining calls
- Forwarding calls
- Save modes
- Versioning
- Builder & Defaults
- ProGuard
- Contributing
- License
Overview
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.
// definition
public interface MyPreferences {
@KeyByString("key_username")
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+).
JAR
Gradle
compile 'net.orange-box.storebox:storebox-lib:1.4.0'
Maven
<dependency>
<groupId>net.orange-box.storebox</groupId>
<artifactId>storebox-lib</artifactId>
<version>1.4.0</version>
</dependency>
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.
public interface MyPreferences {
}
Now you're ready to use StoreBox.create() to obtain an instance.
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 @KeyByString or @KeyByResource.
@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.
@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.
@KeyByString("key_phone_number")
String getPhoneNumber(String defValue);
And using an annotation referencing a default found in the XML resources.
@KeyByString("key_phone_number")
@DefaultValue(R.string.default_phone_number)
String getPhoneNumber();
For some types, such as long, which cannot be added to the resources an integer resource may be used instead.
@KeyByString("key_refresh_interval")
@DefaultValue(R.integer.default_refresh_interval)
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:
BaseBooleanTypeAdapterfor storing as aBooleanBaseFloatTypeAdapterfor storing as aFloatand so on...BaseIntegerTypeAdapterBaseLongTypeAdapterBaseStringTypeAdapterBaseStringSetTypeAdapter(only supported on API11 and newer)
Telling StoreBox which type adapter should be used can be done by adding the @TypeAdapter annotation to the get and set methods.
@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 DateTypeAdapter, UriTypeAdapter, and CustomClassListTypeAdapter 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:
DateDoubleEnumUri
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 @DefaultSharedPreferences annotation can be added to the interface definition for explicitness. Likewise, @ActivityPreferences or @FilePreferences 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.
@ActivityPreferences(mode = PreferencesMode.MULTI_PROCESS)
public interface WelcomeActivityPreferences {
// method definitions here...
}
Advanced
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 @RemoveMethod annotation. The key can be supplied in two ways;
The key can be provided thorough an argument in the method, using either a String or an int in the case of the key being specified in an XML resource.
public interface RemoveMethodExample {
@RemoveMethod
void remove(String key);
Related Skills
node-connect
347.2kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
108.0kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
347.2kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
347.2kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
