WellSql


Source link: https://github.com/yarolegovich/wellsql

WellSql

Android API for working with SQLiteDatabase can be characterized as inconvenient and ugly (at least for me). This library tends to make work with it easier and reduce amount of boilerplate code you perhaps used to write.

Features

  • Just a wrapper for old trusted methods query, insert, delete etc.
  • Generates classes with public static final strings for each column name.
  • Generates mappers for your model (Conversion to ContentValues and from Cursor).
  • In 98% of use cases library takes care of opening/closing db and cursors.
  • Just one reflexive call, nothing critical

Add to your project

In build.gradle for your project add

buildscript {

dependencies {

  classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

}
 
}
 

In build.gradle for your module add

apply plugin: 'com.neenbedankt.android-apt'  dependencies {

compile 'com.yarolegovich:wellsql:1.0.5'
apt 'com.yarolegovich:wellsql-processor:1.0.5' 
}

Table creation and setup

One of the most important features to ease your life is boilerplate code generation. Here are the steps to create a table.

Create your model class, make it implement Identifiable (just two methods - getId() and setId(int id) and configure it with the help of annotations.

@Table @RawConstraints({
"UNIQUE (NAME, fought)"
}
) public class SuperHero implements Identifiable {

@Column
  @PrimaryKey
  private int mId;

@Column @Unique
  private String mName;

@Column(name = "fought")
  @Check("fought >= 0")
  private int mFoughtVillains; 
}

Here is some weird example to show annotations you have in your arsenal. Class also needs getters and setters, so generated mapper can work.

Rebuild your project. Two classes SuperHeroTable and SuperHeroMapper will be generated. You don't need to do anything with the second one, but the first will contain useful fields:

public final class SuperHeroTable implements TableClass {

public static final String ID = "_id";
 public static final String NAME = "NAME";
 public static final String FOUGHT = "fought";
 … 
}

I strongly recommend you to have field id or mId of type int in your model class, or better write custom mappers.

Last step is to create config for WellSql. You will need it to call

WellSql.init(new MyWellConfig(context));

On application startup (extend application class and call this method in overriden onCreate). You can either implement interface WellConfig or extend class DefaultWellConfig (I advice to do the latter, because this class take care of binding with generated classes). Here is an example of how to extend it:

public class WellConfig extends DefaultWellConfig {

public WellConfig(Context context) {

super(context);

  
}

@Override
  public void onCreate(SQLiteDatabase db, WellTableManager helper) {

helper.createTable(SuperHero.class);

helper.createTable(Villain.class);

  
}

@Override
  public void onUpgrade(SQLiteDatabase db, WellTableManager helper, int newVersion, int oldVersion) {

helper.dropTable(SuperHero.class);

helper.dropTable(Villain.class);

onCreate(db, helper);

  
}

@Override
  protected Map<Class<?>, SQLiteMapper<?>> registerMappers() {

return super.registerMappers();

  
}

… 
}

Method registerMethods() can be used to register your custom mappers for classes. If class has generated mapper - it will be ignored, if you pass your own implementation. If you don't need classes to be generated #confused, you can use

@Table(generateMapper = false, generateTable = false) public class Villain implements Identifiable {

… 
}

Usage examples

Builder for queries. You can get results as Map<String, Object>, where keys are column names and values are extracted from cursor. Or results can be converted to model (with the help of automatically generated mappers or your custom mappers.

You can also perform async queries. Result will be delivered to Callback object you provide on the main thread.

/*  * Asynchronously select all from SuperHeroTable  */ WellSql.select(SuperHero.class).getAsModelAsync(new SelectQuery.Callback<List<SuperHero>>() {

  @Override
  public void onDataReady(List<SuperHero> data) {

 assertTrue(Thread.currentThread() == Looper.getMainLooper().getThread());

  
}
 
}
);
  /*  * Some pointless query to show query builder  */ List<SuperHero> heroes = WellSql.select(SuperHero.class)
  .where().greaterThen(SuperHeroTable.FOUGHT, 12)
  .beginGroup().equals(SuperHeroTable.NAME, "Groot").or()
  .equals(SuperHeroTable.NAME, "Rocket Raccoon").endGroup().endWhere()
  .orderBy(SelectQuery.ORDER_DESCENDING, SuperHeroTable.FOUGHT)
  .limit(12)
  .getAsModel();

The same way you can peform insert, update and delete queries.

WellSql.insert(getHeroes()).asSingleTransaction(true).execute();
  WellSql.delete(SuperHero.class).execute();
  WellSql.delete(SuperHero.class).where()
  .greaterThenOrEqual(SuperHeroTable.FOUGHT, 12)
  .endWhere().execute();
  WellSql.update(SuperHero.class).whereId(hero.getId()).put(anotherHero).execute();

Update only one field of a Model:

WellSql.update(SuperHero.class).where()

  .equals(SuperHeroTable.NAME, "Rocket Raccoon").endWhere()

  .put("Yaroslav", new InsertMapper<String>() {

@Override

public ContentValues toCv(String item) {

 ContentValues cv = new ContentValues();

 cv.put(SuperHeroTable.NAME, item);

 return cv;

}

  
}
).execute();

Factory methods of WellSql class covers most use cases (I think so), but if you want to make something unusual with db you can always call

SQLiteDatabase db = WellSql.giveMeReadableDb();
  SQLiteDatabase db = WellSql.giveMeWritableDb();

For more usage examples you can see tests of well-sample, but I think nothing extraordinary in api :)

Licence

MIT licence

Resources

Customisations for the native Android SearchView.

ngAndroid is bringing angularjs type directives to android xml attributes.

PinCodePicker was created for Android platform as a view which allows to take passwords/codes or some other sensitive data from end user in easy way, so developers can focus on the core functionalities of their application.

Android View that displays different content based on its state (Content, Empty, Error, Loading).

The easiest way to create adapters! You can add a lot of different layouts and models. This library avoid all the boilerplates needed to create a list for your application.

Highly inspired on Renderers and RecyclerViewRenderers.

SquiDB is a SQLite database layer for Android. It is designed to make it as easy as possible to work with SQLite databases while still enabling the power and flexibility of raw SQL. SquiDB combines features of an ORM with object-oriented SQL statement builders to make it easy to read and write your data without a bunch of messy SQL strings. It also includes built in tools and hooks to help you easily write database migrations as well as implement ContentProviders.

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