Simple Preferences


Source link: https://github.com/yshrsmz/simple-preferences

Simple Preferences

Simple Preference is a SharedPreference Manager generator.

The library generates code for managing SharedPreferences at compile time with Annotation Processor.
So you don't need to manage SharedPreferences' key string by your hand anymore.

And because getter/setter is generated by Annotation Processor, you can take full advantage of AndroidStudio's auto completion.

Currently the library supports get/ set/ has/ remove operation for each keys( String/ int/ float/ long/ Set<String>), and clear operation for SharedPreference itself.

Installation

SimplePreferences is distributed via jCenter. .
This library requires JDK8 to run annotation processor.

dependencies {

annotationProcessor 'net.yslibrary.simplepreferences:simplepreferences-processor:LATEST_LIBRARY_VERSION'
compile 'net.yslibrary.simplepreferences:simplepreferences:LATEST_LIBRARY_VERSION' 
}

Usage

define ordinary POJO with @Preferences and @Key.

@Preferences public class Config {

// you'd better define these variable as protected to avoid accidental access
@Key
protected int userId = 0;
 @Key
protected String userName = "";
 @Key(omitGetterPrefix = true)
protected boolean isPremium = false; 
}
 

and following class is generated

public class ConfigPrefs extends Config {

private final SharedPreferences prefs;
 private ConfigPrefs(@NonNull Context context) {

  prefs = context.getApplicationContext().getSharedPreferences("config", Context.MODE_PRIVATE);

}

 public static ConfigPrefs create(@NonNull Context context) {

  if (context == null) {

 throw new NullPointerException("Context is Null!");

  
}

  return new ConfigPrefs(context);

}

 public void clear() {

  prefs.edit().clear().apply();

}

 public ConfigPrefs setUserId(int value) {

  prefs.edit().putInt("user_id", value).apply();

  return this;

}

 public int getUserId() {

  return prefs.getInt("user_id", userId);

}

 public int getUserId(int defaultValue) {

  return prefs.getInt("user_id", defaultValue);

}

 public boolean hasUserId() {

  return prefs.contains("user_id");

}

 public ConfigPrefs removeUserId() {

  prefs.edit().remove("user_id").apply();

  return this;

}

 public ConfigPrefs setUserName(String value) {

  prefs.edit().putString("user_name", value).apply();

  return this;

}

 public String getUserName() {

  return prefs.getString("user_name", userName);

}

 public String getUserName(String defaultValue) {

  return prefs.getString("user_name", defaultValue);

}

 public boolean hasUserName() {

  return prefs.contains("user_name");

}

 public ConfigPrefs removeUserName() {

  prefs.edit().remove("user_name").apply();

  return this;

}

 public ConfigPrefs setIsPremium(boolean value) {

  prefs.edit().putBoolean("is_premium", value).apply();

  return this;

}

 public boolean isPremium() {

  return prefs.getBoolean("is_premium", isPremium);

}

 public boolean isPremium(boolean defaultValue) {

  return prefs.getBoolean("is_premium", defaultValue);

}

 public boolean hasIsPremium() {

  return prefs.contains("is_premium");

}

 public ConfigPrefs removeIsPremium() {

  prefs.edit().remove("is_premium").apply();

  return this;

}
 
}

As you may noticed from generated getter method, the values you set in your POJO become default values for each keys.

Also you can provide custom default value with overloaded method.

Generated classes will be placed at the same package as parent classes.

Annotations

@Preferences

Declare annotated class as SharedPreferences model.

parameter description default vale
value SharedPreferences name empty (class name is converted to lower_snake_case and used as SharedPreferences name)
useDefault use DefaultSharedPreferences or not false
needCommitMethodForClear whether or not create additional clear method which uses SharedPreferences.Editor#commit() false
expose whether to make generated classes public or not true

@key

Declare annotated variable as SharedPreferences key.

parameter description default vale
name preference's key name empty (variable name is converted to lower_snake_case and used as key)
omitGetterPrefix whether or not prepend prefix for getter method false (prepend prefix)
needCommitMethod whether or not create additional setter method which use SharedPreferences.Editor#commit() false (disabled)

omitGetterPrefix is useful when you define boolean value.

needCommitMethodForClear/ needCommitMethod is useful when you want to update the backing file synchronously.

License

Copyright 2016-2017 Shimizu Yasuhiro (yshrsmz)  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

The easy way to take screenshots of your application programmatically.

Newtron Watchdog allows the critical applications you develop for Android to keep running even after an application crash.

Love Architecture Components' ViewModels but hate how hard it is to instantiate them?

Hire Alfred and start doing just this!

This project allowing you to create circular and rounded corner imageview in android through simplest way.

It uses a BitmapShader and does not:

  • create a copy of the original bitmap
  • use a clipPath (which is neither hardware accelerated nor anti-aliased)
  • use setXfermode to clip the bitmap (which means drawing twice to the canvas)

This little Project written by Kotlin used Retrofit and Rxjava and so on. Pull data from Readhub which is a news aggregator website in China.

An android custom view for emoji style rating selection.

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