• Stars
    star
    223
  • Rank 178,458 (Top 4 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created about 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Some common utilities for ContentProvider/ContentResolver/Cursor and other db-related android stuff

android-db-commons

WARNING: This library is under heavy development. We can't guarantee both stability of the library itself and the API. However, if you'll find some troubles, bugs, problems please submit an issue here so we can fix it!

Some common utilities for ContentProvider/ContentResolver/Cursor and other db-related android stuff

Currently it's just a builder for ContentResolver-related crap. If you feel tired of this:

getContentResolver().query(uri, 
  new String[] { People.NAME, People.AGE }, 
  People.NAME + "=? AND " + People.AGE + ">?", 
  new String[] { "Ian", "18" }, 
  null
);

or:

getContentResolver().query(uri, null, null, null, null);

Using this lib you can replace it with something like:

ProviderAction.newQuery(uri)
  .projection(People.NAME, People.AGE)
  .where(People.NAME + "=?", "Ian")
  .where(People.AGE + ">?", 18)
  .perform(getContentResolver());

What's next? You may want to transform your Cursor to some collection of something. Using this util you can easily do:

ProviderAction.newQuery(uri)
  .projection(People.NAME, People.AGE)
  .where(People.NAME + "=?", "Ian")
  .where(People.AGE + ">?", 18)
  .perform(getContentResolver());
  .transform(new Function<Cursor, String>() {
    @Override public String apply(Cursor cursor) {
      return cursor.getString(cursor.getColumnIndexOrThrow(People.NAME));
    }
  })
  .filter(new Predicate<String>() {
    @Override public boolean apply(String string) {
      return string.length()%2 == 0;
    }
  });
  

Loaders

Loaders are fine. They do some hard work for you which otherwise you would need to do manually. But maybe they can be even funnier?

This is a standard way of creating CursorLoader.

long age = 18L;
final CursorLoader loader = new CursorLoader(getActivity());
loader.setUri(uri);
loader.setProjection(new String[] { People.NAME });
loader.setSelection(People.AGE + ">?");
loader.setSelectionArgs(new String[] { String.valueOf(age) });

Using android-db-commons you can build it using this builder:

CursorLoaderBuilder.forUri(uri)
  .projection(People.NAME)
  .where(People.AGE + ">?", 18)
  .build(getActivity());

Looks nice, isn't it? Yeah, but it's still not a big change. Anyway, all of us know this:

@Override public void onLoadFinished(Loader<Cursor> loader, Cursor result) {
  RealResult result = ReaulResult.veryExpensiveOperationOnMainUiThread(result);
  myFancyView.setResult(result);
}

Using this library you are able to perform additional operations inside Loader's doInBackground().

private static final Function<Cursor,RealResult> TRANSFORM = new Function<Cursor, RealResult>() {
  @Override public RealResult apply(Cursor input) {
    return RealResult.veryExpensiveOperationOnMainUiThread(result);
  }
};

CursorLoaderBuilder.forUri(uri)
  .projection(People.NAME)
  .where(People.AGE + ">?", 18)
  .transform(TRANSFORM)
  .build(getActivity());

Wanna transform your Cursor into a collection of something? Easy.

private static final Function<Cursor,String> ROW_TRANSFORM = new Function<Cursor, String>() {
    @Override public String apply(Cursor cursor) {
      return cursor.getString(cursor.getColumnIndexOrThrow(People.NAME));
    }
  };

CursorLoaderBuilder.forUri(uri)
  .projection(People.NAME)
  .where(People.AGE + ">?", 18)
  .transformRow(ROW_TRANSFORM)
  .build(getActivity());

Your Loader will return List as a result in this case. But we still can do better - instead of writing simple row transformations by hand we can use a factory method:

import static com.getbase.android.db.cursors.SingleRowTransforms.getColumn;

CursorLoaderBuilder.forUri(uri)
  .projection(People.NAME)
  .where(People.AGE + ">?", 18)
  .transformRow(getColumn(People.NAME).asString())
  .build(getActivity());

What if the Cursor has 100K rows? Transforming it into collection would take way too much time and would have huge memory footprint.

CursorLoaderBuilder.forUri(uri)
  .projection(People.NAME)
  .where(People.AGE + ">?", 18)
  .transformRow(getColumn(People.NAME).asString())
  .lazy()
  .build(getActivity());

The result of this loader is lazy list. We do not iterate through your 100K-rows Cursor. Every row's transformation is calculated at its access time.

Sure, you can still transform() your transformedRows().

// Functions contants here
CursorLoaderBuilder.forUri(uri)
  .projection(People.NAME)
  .where(People.AGE + ">?", 18)
  .transformRow(CURSOR_ROW_TO_STRING)
  .transformRow(STRING_TO_INTEGER)
  .transform(LIST_OF_INTEGER_TO_REAL_RESULT)
  .build(getActivity());

WARNING: Please make sure you don't leak any Fragment/Activities/other resources when constructing your Loader. In Java, all anonymous nested classes are non-static which means that they are holding a reference to the parent class. As the Function instances are cached in created Loader instance (which is being reused among multiple Activities/Fragments instances) using anonymous classes can lead to awful memory leaks or even crashes in runtime.

Example leaking code (let's assume it's Fragment instance):

@Override
public Loader<List<String>> onCreateLoader(int id, Bundle args) {
  CursorLoaderBuilder.forUri(uri)
    .projection(People.NAME)
    .where(People.AGE + ">?", 18)
    .transformRow(new Function<Cursor, String>() { // Leaking Fragment's instance here. DO NOT DO THAT!
      @Override public String apply(Cursor cursor) {
        return cursor.getString(0);
      }
    })
    .build(getActivity());
}

If you don't want to extract all your functions to constants you can use our LoaderHelper that tends to make client's code simpler:

private static final LoaderHelper<List<String>> loaderHelper = new LoaderHelper<List<String>>(LOADER_ID) {
  @Override
  protected Loader<List<String>> onCreateLoader(Context context, Bundle args) {
    return CursorLoaderBuilder.forUri(Contract.People.CONTENT_URI)
        .projection(Contract.People.FIRST_NAME, Contract.People.SECOND_NAME)
        .transformRow(new Function<Cursor, String>() {
          @Override
          public String apply(Cursor cursor) {
            return String.format("%s %s", cursor.getString(0), cursor.getString(1));
          }
        })
        .build(context);
    }
};

And then, when you want to initialize your Loader (let's say in fragment):

// let's assume that 'this' implements LoaderHelper.LoaderDataCallbacks<Result> interface.
loaderHelper.initLoader(getActivity(), bundleArgs, this); 

LoaderHelper.LoaderDataCallbacks' interface is very similar to the one provided by default support-library's LoaderCallbacks so the convertion will be simple and easy.

Wrap function is applyied in Loader's doInBackground() so you don't have to worry about ANRs in case you want to do something more complex in there.

Fluent SQLite API

Concatenating SQL strings is not fun. It's very easy to make a syntax error - miss the space, comma or closing bracket - and cause the runtime error. The other problem arises when you want to modify existing query, for example to apply some filters. To ameliorate this issues, we have created fluent API for basic SQLite operations:

select()
    .columns(People.NAME, People.AGE)
    .from(Tables.PEOPLE)
    .where(column(People.NAME).eq().arg(), "Ian")
    .where(column(People.AGE).gt().arg(), 18)
    .perform(db);

Note that perform() returns FluentCursor, which allows you to easily transform query results into POJOs.

Usage

Just add repository and the dependency to your build.gradle:

dependencies {
    compile 'com.getbase.android.db:library:0.15.0'
}

minSdkVersion = 15

The last with minSdkVersion = 10 was v0.10.1. The last with minSdkVersion < 10 Android versions was v0.6.3.

Other libraries

android-db-commons works even better when combined with some other cool libraries. You may want to try them!

MicroOrm

CursorLoaderBuilder.forUri(myLittleUri)
  .projection(microOrm.getProjection(Person.class))
  .transform(microOrm.getFunctionFor(Person.class))
  .build(getActivity());

Publishing new version

  1. Update VERSION_NAME in gradle.properties file
  2. Merge PR to master
  3. Create new GitHub release with tag name v followed by version - e.g. v0.15.0
  4. GitHub Actions will automatically build and publish new package in Maven repository

Copyright and license

Copyright 2013 Zendesk

Licensed under the Apache License, Version 2.0

More Repositories

1

android-floating-action-button

Floating Action Button for Android based on Material Design specification
Java
6,374
star
2

maxwell

Maxwell's daemon, a mysql-to-json kafka producer
Java
3,989
star
3

cross-storage

Cross domain local storage, with permissions
JavaScript
2,190
star
4

samson

Web interface for deployments, with plugin architecture and kubernetes support
Ruby
1,446
star
5

ruby-kafka

A Ruby client library for Apache Kafka
Ruby
1,269
star
6

helm-secrets

DEPRECATED A helm plugin that help manage secrets with Git workflow and store them anywhere
Shell
1,159
star
7

curly

The Curly template language allows separating your logic from the structure of your HTML templates.
Ruby
594
star
8

biz

Time calculations using business hours.
Ruby
488
star
9

racecar

Racecar: a simple framework for Kafka consumers in Ruby
Ruby
486
star
10

zendesk_api_client_rb

Official Ruby Zendesk API Client
Ruby
387
star
11

dropbox-api

Dropbox API Ruby Client
Ruby
362
star
12

zendesk_api_client_php

Official Zendesk API v2 client library for PHP
PHP
335
star
13

stronger_parameters

Type checking and type casting of parameters for Action Pack
Ruby
297
star
14

active_record_shards

Support for sharded databases and replicas for ActiveRecord
Ruby
250
star
15

delivery_boy

A simple way to publish messages to Kafka from Ruby applications
Ruby
238
star
16

radar

High level API and backend for writing web apps that use push messaging
JavaScript
221
star
17

sunshine-conversations-web

The Smooch Web SDK will add live web messaging to your website or web app.
212
star
18

demo_apps

HTML
179
star
19

arturo

Feature Sliders for Rails
Ruby
174
star
20

belvedere

An image picker library for Android
Java
146
star
21

zendesk_jwt_sso_examples

Examples using JWT for Zendesk SSO
Ruby
142
star
22

sunshine-conversations-ios

Smooch
Objective-C
122
star
23

laika

Log, test, intercept and modify Apollo Client's operations
TypeScript
122
star
24

prop

Puts a cork in their requests
Ruby
117
star
25

zendesk_sdk_ios

Zendesk Mobile SDK for iOS
Objective-C
117
star
26

zopim-chat-web-sdk-sample-app

Zendesk Chat Web SDK sample app developed using React
JavaScript
98
star
27

copenhagen_theme

The default theme for Zendesk Guide
Handlebars
98
star
28

app_scaffold

A scaffold for developers to build ZAF v2 apps
JavaScript
90
star
29

node-publisher

A zero-configuration release automation tool for Node packages inspired by create-react-app and Travis CI.
JavaScript
75
star
30

zendesk_apps_tools

Ruby
74
star
31

zendesk_app_framework_sdk

The Zendesk App Framework (ZAF) SDK is a JavaScript library that simplifies cross-frame communication between iframed apps and the Zendesk App Framework
JavaScript
72
star
32

ios_sdk_demo_apps

This repository contains sample iOS code and applications which use our SDKs
Swift
64
star
33

zendesk_sdk_chat_ios

Mobile Chat SDK for iOS
Objective-C
63
star
34

kamcaptcha

A captcha plugin for Rails
Ruby
63
star
35

zcli

A command-line tool for Zendesk
TypeScript
62
star
36

linksf

A mobile website to connect those in need in to services that can help them
JavaScript
62
star
37

sdk_demo_app_android

This is Remember The Date, an Android demo app for our Mobile SDK. All docs available on developer.zendesk.com
Java
61
star
38

property_sets

A way to store attributes in a side table.
Ruby
51
star
39

go-httpclerk

A simple HTTP request/response logger for Go supporting multiple formatters.
Go
51
star
40

android-schema-utils

Android library for simplifying database schema and migrations management.
Java
48
star
41

android_sdk_demo_apps

This repository contains sample android code and applications which use our SDKs
Java
46
star
42

statsd-logger

StatsD + Datadog APM logging server for development - standalone or embedded
Go
44
star
43

sunshine-conversations-android

Smooch Android SDK
42
star
44

support_sdk_ios

Zendesk Support SDK for iOS
Objective-C
37
star
45

react-native-sunshine-conversations

React Native wrapper for Smooch.io
Java
36
star
46

docker-logs-tail

Docker Logs Tail simultaneously tails logs for all running Docker containers, interleaving them in the command line output
JavaScript
35
star
47

call_center

Ruby
34
star
48

curlybars

Handlebars.js compatible templating library in Ruby
Ruby
34
star
49

kasket

A caching layer for ActiveRecord. Puts a cap on your queries!
Ruby
33
star
50

ruby_memprofiler_pprof

Experimental memory profiler for Ruby that emits pprof files.
C
33
star
51

method_struct

Ruby
33
star
52

samlr

Clean room implementation of SAML for Ruby
Ruby
31
star
53

sdk_demo_app_ios

This is Remember The Date, an iOS demo app for our Mobile SDK. All docs available on developer.zendesk.com
Objective-C
31
star
54

volunteer_portal

An event calendar focused on tracking and reporting volunteering opportunities
JavaScript
29
star
55

classic_asp_jwt

A JWT implementation in Classic ASP
ASP
29
star
56

basecrm-ruby

Base CRM API Client
Ruby
29
star
57

ultragrep

the grep that greps the hardest.
C
28
star
58

chariot-tooltips

A javascript library for creating on screen step by step tutorials.
JavaScript
26
star
59

clj-headlights

Clojure on Beam
Clojure
26
star
60

sunshine-conversations-javascript

Javascript API for Sunshine Conversations
JavaScript
26
star
61

android-autoprovider

Utility for creating ContentProviders without boilerplate and with heavy customization options.
Java
25
star
62

basecrm-php

Base CRM API client, PHP edition
PHP
24
star
63

migration_tools

Rake tasks for Rails that add groups to migrations
Ruby
23
star
64

large_object_store

Store large objects in memcache or others by slicing them.
Ruby
22
star
65

term-check

A GitHub app which runs checks for flagged terminology in GitHub repos
Go
22
star
66

basecrm-python

BaseCRM API Client for Python
Python
22
star
67

sdk_unity_plugin

This repository contains a unity plugin which wraps the Zendesk support SDKs
Objective-C
22
star
68

jazon

Test assertions on JSONs have never been easier
Java
21
star
69

ipcluster

Node.js master/worker clustering module for sticky session load balancing using IPTABLES
JavaScript
21
star
70

sunshine-conversations-python

Smooch API Library for Python
Python
21
star
71

cloudwatch-logger

Connects standard input to Amazon CloudWatch Logs
Go
20
star
72

forger

Android library for populating the ContentProvider with test data.
Java
19
star
73

radar_client

High level API and backend for writing web apps that use push messaging
JavaScript
19
star
74

double_doc

Write documentation with your code, to keep them in sync, ideal for public API docs.
Ruby
18
star
75

pakkr

Python pipeline utility library
Python
18
star
76

chat_sdk_ios

Zendesk Chat SDK
Objective-C
18
star
77

goship

Utility that helps find, connect and copy to particular cloud resources using configured providers
Go
18
star
78

url_builder_app

A Zendesk App to help you generate links for agents.
JavaScript
18
star
79

sunshine-conversations-api-quickstart-example

Sample code to get started with the Smooch REST APIs
JavaScript
17
star
80

sunshine-conversations-desk

A sample business system built with Meteor and the Smooch API
CSS
17
star
81

apt-s3

apt method for private S3 buckets
Go
17
star
82

api_client

HTTP API Client Builder
Ruby
16
star
83

zendesk_apps_support

Ruby
16
star
84

iron_bank

An opinionated Ruby interface to the Zuora REST API
Ruby
15
star
85

private_gem

Keeps your private gems private
Ruby
15
star
86

active_record_host_pool

Connect to multiple databases using one ActiveRecord connection
Ruby
15
star
87

sdk_messaging_ios

The Zendesk Messaging SDK
Objective-C
14
star
88

rate_my_app_ios

An open source version of the Rate My App feature from 1.x versions of the Support SDK.
Swift
14
star
89

input_sanitizer

A gem to sanitize hash of incoming data
Ruby
14
star
90

sunshine-conversations-conversation-extension-examples

A series of examples using Smooch conversation extensions
HTML
14
star
91

scala-flow

A lightweight library intended to make developing Google DataFlow jobs in Scala easier.
Scala
14
star
92

punchabunch

Punchabunch: A highly concurrent, easily configurable SSH local-forwarding proxy
Go
14
star
93

zendesk-jira-plugin

Java
13
star
94

sunshine-conversations-ruby

Smooch API Library for Ruby
Ruby
13
star
95

samson_secret_puller

kubernetes sidecar and app to publish secrets to a containerized app.
Ruby
13
star
96

sqlitemaster

Android library for getting existing db schema information from sqlite_master table.
Java
13
star
97

sunshine-conversations-wordpress

PHP
13
star
98

predictive_load

Ruby
12
star
99

sunshine-conversations-api-spec

Sunshine Conversations OpenAPI Specification for v2+
12
star
100

zombie_record

A soft-delete library
Ruby
12
star