PrefData


Source link: https://github.com/xelevra/prefdata

Pref Data – the Android SharedPreferences wrapper

HelloWorld

  1. Create a class and annotate it with @PrefData
@PrefData public abstract class UserSettings {

  // the fields must be protected or package private
  int age;
  String name; 
}
  1. Create an instance of the generated class (it will be prefixed by "Prefs")
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
 PrefUserSettings userSettings = new PrefUserSettings(prefs);

Download

annotationProcessor 'org.xelevra.libs:prefdata-processor:2.2' provided 'org.xelevra.libs:prefdata-annotations:2.2'

Usage

Get and Set
int age = userSettings.getAge();
 userSettings.setAge(18);
Chains
userSettings.setAge(18).setName("Stephen");
Default value

Initial value of your fields will be default values.

int age = 18;
Clear

For clearing the preferences use clear()

Support remove

Mark the class with @GenerateRemove and remove methods will be generated

userSettings.removeAge();
Prefix

Mark your field with @Prefixed annotation

@Prefixed int childAge;

Then use

userSettings.setChildAge("James", 13);
 userSettings.setChildAge("Anna", 15);
Buffered edition
userSettings.edit().setAge(18).setName("Stephen").apply();

Note Until you not called edit() all values will be saved immediatly. When you call edit() all next settings will be saved after calling apply() or commit()

Example:

userParams.edit().setAge(32).setName("Bob").apply();
Custom keywords

Mark the field with @Keyword for custom SharedPreferences key. For example it might help you to migrate to the library from manual preferences setting.

@Keyword("NAME");
 String name;
Custom methods for changing settings

If you have to set some settings from a model or you have to limit actions under the fields you can encapsulate getter or setter for a field and write a custom method:

@Encapsulate String name; @Encapsulate(getter = false) // generate only getter String surname;  @Use({
"name", "surname"
}
) public void setNameAndSurname(String ns){

  name = ns.substring(0, ns.indexOf(" "));

  surname = ns.substring(ns.indexOf(" ") + 1, ns.length());
 
}
  @Use("name") public String getCapitalisedName(){

  return name.toUpperCase();
 
}
Limit the range of allowed values

For the limiting possible values for field, use @Belongs annotation. Example:

@Belongs("animals", "plants", "fungi", "chromista", "protist") String eukaryoteKingdom  @Belongs("-1", "0.43", "54.444f") float randomNumber

The IllegalArgumentException will be thrown if user set a value not from the list. Also you might turn of the checking if set validation = false.

Supported types

Already supported only primitive types and String

Advanced

The library covers another important task you might need: set up some settings to the test builds without rebuilding. Usually programmers includes a special screen with the list of settings, and a tester should do some tricky actions to open it. The library let you take your settings out and manage them using special application provided with it. For the settings with @Belongs the list of available values in the app represented as a selector.

  1. Add dependency
compile 'org.xelevra.libs:prefdata-provider:2.2'
  1. Mark the class or aspecial fields with @Exportable
  2. Extend the abstract class PreferencesContentProvider
public class UserSettingsProvider extends PreferencesContentProvider {

  @Override
  protected Exporter getExporter() {

return new PrefUserSettings(getContext().getSharedPreferences("main", Context.MODE_PRIVATE));

  
}
 
}
  1. Register it in your manifest
<provider

 android:name=".UserSettingsProvider"

 android:authorities="org.xelevra.prefdata.com.example.test"

 android:exported="true"/>

Important In authorities you must write exactly the line started with "org.xelevra.prefdata." and end with your package name. Otherwice the browser app won't find your provider.

Resources

A simple and useful android library to use custom fonts in android apps without adding fonts into asset/resource folder. Also by using this library developer should not have to worry about Typeface object creation for every new font that he use.

Small Android library to simplify common used patterns in view inflation. Using AutoInflateLayout header and footer can be added to ListView.

Cheerleader is an Android open source library designed to easily support an artist in an Android application thanks to a SoundCloud account.

IntentBuilder is a type safe way of creating intents and populating them with extras. Intents were created to be very dynamic but often times the dynamic nature of intents is not needed and just gets in the way of writing safe code.

Simple Visualizer from mic input for Android.

A material Switch with icon animations and color transitions.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes