Creating database in Android – The easier way with SugarOrm

Creating databases and database migration in android can be cumbersome and time-consuming.  SugarOrm is a database persistence library that provides a simple and concise way to integrate your application models into SQLite. With SugarOrm all you have to do is just:

Download/Install

SugarOrm is available on maven central, so installing it is easy as adding compile 'com.github.satyan:sugar:1.3'to your build.gradle file.

Configure

To configure your application to use SugarOrm, you need to add android:name attribute of the application tag in yourAndroidManifest.xml like below:

<application 
    android:label="@string/app_name" 
    android:icon="@drawable/icon"
    android:name="com.orm.SugarApp">
    .
    .
    <meta-data android:name="DATABASE" android:value="sugar_example.db" />
    <meta-data android:name="VERSION" android:value="2" />
    <meta-data android:name="QUERY_LOG" android:value="true" />
    <meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="com.example" />
    .
    .
</application>

Integrate

Integrating SugarOrm into your application is dead simple, just extend SugarRecord<YourModel>, that’s it, then allow SugarOrm to work it magic. Do not forget to retain the default public constructor:

public class Topic extends SugarRecord<Topic> {
  String name;
  String description;

  public Topic(){
  }

  public Topic(String name, String description){
    this.name = name;
    this.description = description;
  }
}

The above would create a corresponding table called topic, with column name and description. If you want SugarOrm to skip a property from persisting, simply annotate it as Ignore:

public class Topic extends SugarRecord<Topic> {
  String name;
  String description;
  @Ignore
  String date;
  .
  .
  .

in the above example, date would not be persisted neither would there be a corresponding column for it.

Perform CRUD operations

Performing CRUD operations are very simple. Functions like save()delete(), find(), findById(..), listAll() and deleteAll() are provided to make the work easy.

Save Entity:

Topic topic = new Topic("Name", "Description")
 topic.save();

Load Entity:

Topic topic = Topic.findById(Topic.class, 1);

Update Entity:

Topic topic = Topic.findById(Topic.class, 1);
 topic.name = "updated name "; // modify the values
 topic.description = "Updated description";
 topic.save(); // updates the previous entry with new values.

Delete Entity:

Topic topic = Topic.findById(Topic.class, 1);
 topic.delete();

Bulk Operations:

List<Topic> topic = Topic.listAll(Topic.class);

 Topic.deleteAll(Book.class);

SugarOrm also supports SQLite query out of the box. With the help of query builder, you can write your own SQLite query. It also has support for creating migration and maintaining database versioning in android.