KVS Schema


Source link: https://github.com/rejasupotaro/kvs-schema

KVS Schema

KVS Schema is a library to manage key-value data for Android. This library generates accessor methods of SharedPreferences from schema class in compile time.

How to use

Create Schema

Let's say you will store user id, You have to create a schema class like below.

@Table(name = "example") public class ExamplePrefsSchema {

  @Key(name = "user_id") int userId; 
}

Class name should be *Schema.

KVS Schema generates ExamplePrefs from ExamplePrefsSchema. You can use generated accessors below.

ExamplePrefs prefs = ExamplePrefs.get(context);
 prefs.putUserId(userId);
 prefs.putUserId(userId, defaultValue);
 prefs.getUserId();
 prefs.hasUserId();
 prefs.removeUserId();

KVS supports boolean String float int long String set.

Default Values

You can specify default values for the case of that a given key doesn't be contained in a SharedPreferences.

prefs.getUserId(defaultValue);

You can also specify default values through a schema class. KVS Schema can read right values that become a constant in compile time.

@Table(name = "example") public abstract class ExamplePrefsSchema {

  @Key(name = "user_id") final int userId = -1; 
}

Using the mechanism, you don't have to specify default values when you set right values that is a final field initialized to a compile time constant.

Serializer

Sometimes you want to put model classes into SharedPreferences. For that cases, KVS Schema can store data using serializer class.

// Schema class @Table(name = "example") public abstract class ExamplePrefsSchema {

  @Key(name = "user", serializer = UserPrefsSerializer.class) String user; 
}
  // Serializer class public class UserSerializer implements PrefsSerializer<User, String> {

  @Override public String serialize(User src) {
 return GSON.toJson(src);
 
}

  @Override public User deserialize(String src) {
 return GSON.fromJson(src, User.class);
 
}
 
}
  // Usage prefs.putUser(user);

Builder

You can specify builder class to use custom SharedPreferences.

// Schema class @Table(name = "example", builder = ExamplePrefsBuilder.class) public abstract class ExamplePrefsSchema {

  @Key(name = "user_id") int userId; 
}
  // Builder class public class ExamplePrefsBuilder implements PrefsBuilder<ExamplePrefs>?{

  @Override
  public ExamplePrefs build(Context context) {

...

return new ExamplePrefs(...);
 // You can pass your SharedPreferences here
  
}
 
}

Using from Kotlin

KVS Schema generates set* method as an alias of put* to utilize property syntax of Kotlin. So you can read/write values like below when you use Kotlin.

prefs.userId = "Kotlin" prefs.userId // => Kotlin

Installation

Add dependencies to your build.gradle.

apt 'com.rejasupotaro:kvs-schema-compiler:5.0.1' compile 'com.rejasupotaro:kvs-schema:5.0.1'

Migration

Even if you have already used SharedPreferences directly in your existing app, migration is easy. KVS Schema simply maps the structure of SharedPreferences.

For example, if you are using default SharedPreferences like below,

prefs = PreferenceManager.getDefaultSharedPreferences(this);
 Editor editor = prefs.edit();
 editor.putString("user_id", "1");
 editor.putString("user_name", "Smith");
 editor.apply();

your data is saved on path/to/app/shared_prefs/package_name_preferences.xml. The schema class becomes like below.

@Table(name = "package_name_preferences") public abstract class ExamplePrefsSchema {

  @Key(name = "user_id") int userId;
  @Key(name = "user_name") String userName; 
}

See a concrete example: https://github.com/konifar/droidkaigi2016/pull/311

In addition, SharedPreferencesInfo may help you to migrate from existing apps. You can get existing SharedPreferences through SharedPreferencesInfo.getAllPrefsAsTable.

List<SharedPreferencesTable> tables = SharedPreferencesInfo.getAll(this);

for (SharedPreferencesTable table : tables) {

 Log.d("DEBUG", table.toString());

}

You can see what kind of data is saved in your app like below.


name: com.example.android.kvs_preferences
 path: /data/data/com.example.android.kvs/shared_prefs/com.example.android.kvs_preferences.xml  ?????????????????????????????????????  ? Key

 ? Value

  ? Type
?  ?????????????????????????????????????  ? user_name ? Smith

  ? String ?  ?????????????????????????????????????  ? user_id
? 1

? String ?  ????????????????????????????????????? 

Resources

Fluent design by contract assertions for Android.

Library for passing arguments into Fragment.

Local network library for connecting Android devices on WiFi. One device serves as a server, others are clients. Library takes care of discovery of server by clients and it uses services and separate threads with sockets to handle communication.

Analytics framework for Android.

This is a sample project showing an implementation of mini navigation drawer for Android.

An implementation of tap targets from the Material Design guidelines for feature discovery.

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