Skip to content

SharedPreferencesHelpers

pyricau edited this page Jan 13, 2012 · 7 revisions

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 an activity with the @Pref annotation.

@EActivity
public class MyActivity extends Activity {

	@Pref
	MyPrefs_ myPrefs;
	
	// ...

}

You can then start using it:

myPrefs.name().put("John");
myPrefs.edit() //
                                .name() //
                                .put("John") //
                                .age() //
                                .put(42) //
                                .apply();

Please note that shared prefs can only be used in activities, due to some compiler specific hairy bugs. If you really think you'd need to use them in another kind of component, please let us know by raising an issue.

If you need more details, Old Issue 47 should give you enough information to get started.

You could also have a look at the functional tests.

Using AndroidAnnotations

Questions?

Enjoying AndroidAnnotations

Improving AndroidAnnotations

Clone this wiki locally