TypedPreferences


Source link: https://github.com/markusressel/TypedPreferences

TypedPreferences

A simple library to make the use of Android's SharedPreferences easier while keeping it type safe. For base types this library only uses generics to provide type safety. However it is also possible to use more complex classes as types. Those will be serialized to json using the GSON library ( Link) before saving them to SharedPrefrences.

This library was designed to be used with a Dependency Injection Framework like Dagger 2 ( Link) and Lombok ( GitHub, Examples) for boilerplate code generation in mind. If you have never used one of those tools I highly recommend looking into them before you start building your app.

Build Status

Master Beta Dev

How to use

Have a look at the demo app ( app module) for a complete sample. The sample app uses Dagger 2 to inject the PreferenceHandler into the activity and fragment. Using DI is the recommended way to use this library.

Gradle

To use this library just include it in your depencencies using

repositories {

  ...
  maven {
 url "https://jitpack.io" 
}
 
}
 

in your project build.gradle file and

dependencies {

  compile('com.github.markusressel:TypedPreferences:v1.1.0') {

exclude module: 'app'

transitive = true
  
}
 
}
 

in your desired module build.gradle file.

Create a PreferenceHandler

The first thing you have to do to get started is creating a class which extends the provided PreferenceHandlerBase class. Override the necessary methods like getSharedPreferencesName() to provide the name of your SharedPreferences file and getAllPreferenceItems() to return a list of all your PreferenceItems.

A simple example would look something like this:

@Singleton public class PreferenceHandler extends PreferencesHandlerBase {

public static final PreferenceItem<Boolean> BOOLEAN_SETTING = new PreferenceItem<>(R.string.key_boolean_setting, true);

  public static final PreferenceItem<ComplexClass> COMPLEX_SETTING = new PreferenceItem<>(R.string.key_complex_setting, new ComplexClass("default", 0);

private List<PreferenceItem> allPreferences;

@Inject
  public PreferenceHandler(Context context) {

super(context);

 allPreferences = new LinkedList<>();

allPreferences.add(BOOLEAN_SETTING);

allPreferences.add(COMPLEX_SETTING);

  
}

@NonNull
  @Override
  public String getSharedPreferencesName() {

return "preferences";
  
}

@NonNull
  @Override
  public List<PreferenceItem> getAllPreferenceItems() {

return allPreferences;
  
}
 
}
 

Define your PreferenceItems

To make accessing your preferences as easy as possible define them by declaring a PreferenceItem in your PreferenceHandler or any other accessible place.

public static final PreferenceItem<Boolean> BOOLEAN_SETTING = new PreferenceItem<>(R.string.key_boolean_setting, true);
 

Important to note here is that the key is not a String but a StringRes ( int) that you define in your strings.xml. This makes it possible to also use this value in a PreferenceFragment like shown in the example app. The generic type will be inferred from the default value, which therefore must not be null. Otherwise you'd have to specify the type manually which would reduce type safety.

Since v1.1 the type of your PreferenceItem is not limited to base types anymore but can be any class extending Object. If needed your custom object will be serialized to json using the GSON library ( Link) and then saved to the SharedPreferences as a String. Refer to the GSON User Guide for more info on what types are fully serializable by GSON.

Get a stored value

To retrieve a value use the getValue(PreferenceItem preferenceItem) method of your PreferenceHandler:

Boolean value = preferenceHandler.getValue(PreferenceHandler.BOOLEAN_SETTING);
 

If possible the result type will be detected automatically. If this doesn't work for some reason (f.ex. because you are accessing a generic PreferenceItem) you can specify the return type using the basic java <> syntax. This will break type safety though and should only be used as a last resort.

Example:

String key = "boolean_setting"; PreferenceItem preferenceItem = preferenceHandler.getPreferenceItem(key);
  Boolean value = preferenceHandler.<Boolean>getValue(preferenceItem);
 

You may use any type you want, f.ex.:

ComplexClass value = preferenceHandler.getValue(PreferenceHandler.COMPLEX_SETTING);
 

Keep in mind though that saving base types like Boolean, Integer, Long, Float, String is always preferable to using complex classes that need serialization before they can be saved. Base types are saved without json serialization and can therefore be saved and requestet much faster.

Set a new value

To set a new value use the setValue(preferenceItem, newValue) method:

preferenceHandler.setValue(PreferenceHandler.BOOLEAN_SETTING, true);
 

The target type of your preference will be detected automatically from the default value of your PreferenceItem. If the type of newValue is not the expected one this line will show an error at compile time.

Another example for using a complex class type:

preferenceHandler.setValue(PreferenceHandler.COMPLEX_SETTING, new ComplexClass("text", 10));
 

Troubleshooting

If you are using a custom class as the type of your PreferenceItem make sure it can be parsed by the GSON library. Refer to the GSON User Guide for more info on what types are fully serializable by GSON.

Contributing

Github is for social coding: if you want to write code, I encourage contributions through pull requests from forks of this repository. Create Github tickets for bugs and new features and comment on the ones that you are interested in.

License

Copyright (c) 2017 Markus Ressel  Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License. You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

Resources

Static code analysis plugin for Android projects.

Android Http Client is a small library to make requests to any internet service simple and practical way. You can implement multiple interfaces for the management of the responses. It also includes interfaces for managing upload and download of files.

Tool to convert CSV to localization specific files (ios/android).

Interactive step paging indicator widget, compatible with the ViewPager.

This is a reference guide for Android Security things.

Crate is a simple gradle plugin to generate a list of classes for all files/folders included in your projects assets directory, for compile time safety. This is how the R classes used for referencing resources work. It also has the advantage of removing the need to use the notoriously slow AssetManager.list() methods.

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