SharedPreferencesHelpers - PerfectCarl/androidannotations GitHub Wiki
Since AndroidAnnotations 2.1
SharedPreferences helpers allow you to use Android SharedPreferences, but in a typesafe manner, instead of using strings.
Defining the preferences
First, you should create an interface annotated with @SharedPref
to define the SharedPreferences :
@SharedPref
public interface MyPrefs {
// The field name will have default value "John"
@DefaultString("John")
String name();
// The field age will have default value 42
@DefaultInt(42)
int age();
// The field lastUpdated will have default value 0
long lastUpdated();
}
Based on that specification, AndroidAnnotations builds a SharedPreferences Helper that has the same name plus an underscore. You can get an instance of the generated helper in any enhanced class with the @Pref
annotation.
Important: The type of the field MUST be the generated class instead of the source class. It's the only exception in AA.
@EActivity
public class MyActivity extends Activity {
@Pref
MyPrefs_ myPrefs;
// ...
}
You can then start using it:
// Simple edit
myPrefs.name().put("John");
// Batch edit
myPrefs.edit()
.name()
.put("John")
.age()
.put(42)
.apply();
// Preference clearing:
myPrefs.clear();
// Check if a value exists:
boolean nameExists = myPrefs.name().exists();
// Reading a value
long lastUpdated = myPrefs.lastUpdated().get();
// Reading a value and providing a fallback default value
long now = System.currentTimeMillis();
long lastUpdated = myPrefs.lastUpdated().getOr(now);
Default resource value
Since AndroidAnnotations 3.0
It's now possible to inject a default value from Android resources with @DefaultRes
:
@SharedPref
public interface MyPrefs {
@DefaultRes(R.string.defaultPrefName)
String resourceName();
@DefaultRes
String defaultPrefAge();
}
Scope
Observe that you can name the shared preference by setting value
to one of the following:
ACTIVITY
, for a shared preference namedMyActivity_MyPrefs
;ACTIVITY_DEFAULT
, for a shared preference namedMyActivity
(also available throughactivity.getPreferences()
);APPLICATION_DEFAULT
, for the defaultSharedPreference
orUNIQUE
, for a shared preference namedMyPrefs
.
Therefore, if a single shared preference is needed for the interface defined, in order to all activities of a given application to share the same preferences, the following should be used:
@SharedPref(value=SharedPref.Scope.UNIQUE)
public interface MyPrefs {
...
PreferenceActivity
Using it with a The Android PreferenceActivity
can edit the values of your shared preferences.
@SharedPref()
public interface MyPrefs {
...
}
public class PrefsActivity extends PreferenceActivity {
public static String PREF_NAME = "MyPrefs";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Using your MyPrefs values
this.getPreferenceManager().setSharedPreferencesName(PREF_NAME);
// Opening the layout
addPreferencesFromResource(R.xml.prefs);
}
}