SharP wraps your SharedPreferences into a clean, type-safe Java interface. It uses annotation processing to generate the boilerplate code for you.
Just declare your interface and annotate it to be a @SharedPreference
or a @DefaultSharedPreference
:
@SharedPreference
interface LocalStorage{
String getMyStringPreference();
void setMyStringPreference(String value);
int getMyIntPreference();
void setMyIntPreference(int value);
}
...then instantiate its auto-generated implementation using SharP
:
LocalStorage storage = SharP.getInstance(context, LocalStorage.class);
String myStringPreference = storage.getMyStringPreference();
int myIntPreference = storage.getMyIntPreference();
storage.setMyStringPreference("FooBar");
storage.setMyIntPreference(42);
That's it. No struggling with keys anymore.
Please refer to the Javadoc or the sample application for more information.
##Usage SharP is available via jcenter()
. The android-apt plugin is used to setup SharP as annotation processor in Android Studio.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.6'
}
}
apply plugin: 'com.neenbedankt.android-apt'
dependencies {
compile 'de.ad:sharp-api:0.3.0'
apt 'de.ad:sharp-processor:0.3.0'
}
##Principles In order to be lightweight and convenient SharP is designed according to the Convention over Configuration paradigm.
###Conventions ####Interface
@DefaultSharedPreference
:- The default
SharedPreferences
are used callingPreferencesManager.getDefaultSharedPreferences(Context context)
- Use this if you want to access the stored preferences from PreferenceFragment
@SharedPreference
:- Preferences are stored in their own file in
MODE_PRIVATE
- The fully qualified
interface
name is used as unique filename - Only top-level interfaces are supported
####Properties
- JavaBean naming conventions are applied
- Getters are required to:
- start with
get
and - have no parameters
- Example:
String getMyStringPreference();
- Boolean getters are required to:
- start with
is
- have no parameters and
- must return
boolean
- Example:
boolean isMyBooleanPreference();
- Setters are required:
- to start with
set
- have exactly one parameter
- must return
void
- Example:
void setMyStringPreference(String value);
- Each getters needs a corresponding setter
- Example:
int getMyIntPreference()
requires declaration ofvoid setMyIntPreference(int value)
####Supported types
- SharP supports all types, but there is a twofold distinction:
- Native types (
int
,long
,float
,boolean
andString
) - Custom types (any non native type)
- While native types are natively supported by SharedPreferences, custom types will be serialized/deserialized and treated as
String
####Default values
- If a value has not been set yet, Java's default values are returned according to its type
####Specialities
- The declaration of
void reset()
in your interface will result in a special implementation which callseditor.clear().apply()