Persistence


Source link: https://github.com/casidiablo/persistence

This library works as a SQLite wrapper and allows you to easily create, query and work with schemas based on objects. This means you can forget about handling queries and Cursors manually, and work directly with Java classes.

Maven integration

In order to use this library from you Android project using maven your pom should look like this:

<?xml version="1.0" encoding="UTF-8"?> <project ...>
  <dependencies>

<dependency>

 <groupId>com.codeslap</groupId>

 <artifactId>persistence</artifactId>

 <version>0.9.23</version>

 <scope>compile</scope>

</dependency>
  </dependencies> </project>

Normal integration

Refer to the downloads section to get a JAR to import to your project.

Get started

Create a class that extends android.app.Application like this:

public class App extends Application {

  @Override
  public void onCreate() {

super.onCreate();

DatabaseSpec database = PersistenceConfig.registerSpec(/**db version**/1);

database.match(Foo.class, Bar.class);

  
}
 
}

And add this to your manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

  package="your.package.name"

  ...>
  <application ...

android:name="your.package.name.App">

...

Here Foo and Bar are POJOs that you will use within your app. Persistence library will automatically create sqlite tables for those classes, which will allow you to insert, query, update and delete data easily:

In order to interact with the database, you must get an implementation of the SqlAdapter interface. You can do so this way:

SqlAdapter adapter = Persistence.getAdapter(context);

Inserting/updating data

To insert a simple object to the database use the store method:

// single insertion Foo foo = new Foo();
 // add data to your object foo.setExample(...);
 adapter.store(foo);

Notice: if you are inserting an object of type Foo, you must have already registered that class in the Application class.

If you want to store a collection of beans use the storeCollection(list, listener) method:

List<Foo> foos = new ArrayList();
 // foos.add(foo);
 adapter.storeCollection(null, new ProgressListener() {

  @Override
  public void onProgressChange(int percentage) {

  
}
 
}
);

This is much more efficient than implementing a loop manually since this will not insert items one-by-one but instead will create a bulk insert statement. There is another version of this method called storeUniqueCollection which basically inserts and updates objects that you pass into the list, and delete from the database those items that are not included in the list.

When you insert an object whose primary key is not auto-increment, it will try to update it instead of inserting a new one. In other cases use the update method:

City sample = new City();
 sample.setName("vogota");
  City newCity = new City();
 newCity.setName("Bogotá");
  adapter.update(newCity, sample);

Notice that update method can also be used with raw SQL statements and Android wildcards.

Querying data

You can query single objects or a collection of objects:

// query a single item by example City city = new City();
 city.setName("Bogotá");
 City bogota = adapter.findFirst(city);

You can also use raw SQL queries:

City bogota = adapter.findFirst(City.class, "name LIKE 'Bogotá'", null);
 // although it is recommended to use Android's wildcards: City bogota = adapter.findFirst(City.class, "name LIKE ?", new String[]{
"Bogotá"
}
);

Use findAll to get a list of objects that matches some conditions:

// Query all cities List<City> cities = adapter.findAll(City.class);
  // Query cities that match a sample City sample = new City();
 sample.setCountryCode("CO");
 List<City> colombianCities = adapter.findAll(sample);
  // You can set some constraints Constraint constraint = new Constraint().limit(3).groupBy("column").orderBy("name");
 List<City> someCities = adapter.findAll(sample, constraint);

Deleting data

Just use the delete method:

// this will truncate the table... adapter.delete(City.class, null, null);
  // this is a better way to truncate a table... adapter.truncate(City.class);
  // this will delete the items that match the sample City sample = new City();
 sample.setCountryCode("CO");
 adapter.delete(sample);

Examples

Looking for examples? You might take a look at Github Jobs app.

Feedback

If you have any questions or suggestions do not hesitate to sending me an email about it ( [email protected]). Keep in mind that this project is in beta phase and I do not warranty it will work as expected.

Resources

Quote it is a social platform for sharing quotes and wise sayings. It is great to share and spread the wisdom and thought full.

Are you tired of searching images for your Android app and copying each image file into its own drawable folder? I had the same problem and each icon I have copied I thought that I am wasting my time. Especially when Google published their big "Material Design Icon" pack. Nearly 70,000 icons in too many folders. So I thought that I need a tool which reads all icons of a folder and give me the chance to copy them easily into my project drawable folder. And here it is :-)

This tiny library lets you easily send Android Intents to the main Evernote app.

A simple rest API client library.

Some common classes for use in your android projects.

A library to display videos in a TextureView using a custom MediaPlayer controller.

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