Sugar : Android database made easy.

UPDATE : Some of the code snippets in the below post are outdated. Please visit http://satyan.github.com/sugar/ for latest updates to the library.

This post is an introduction to Sugar library for android. The aim of the project is to simplify database access in Android.

The project draws inspiration from GORM for grails or Active Record for Rails. These patterns have been hugely successful in the web world, and have set a benchmark for libraries for database access.

The basic objectives of the library  are:

1. Creation and management of database and connection.

2. Simple and Intuitive API for database querying.

3. Simple CRUD operations.

Source Code

Source code is present at https://github.com/satyan/sugar

You can clone it and start hacking. There’s a build script along with it to compile and generate the binary.

An example project using the library is present at https://github.com/satyan/SugarExample

Usage

Android Manifest file: 

Include the android:name attribute in the application tag. SugarApp extends android’s Application and initiates the database creation for the project. By including the attribute, you’re basically starting with SugarApp instead of android’s Application class. If you intend to write your own Application class, you can extend SugarApp.

<?xml version="1.0" encoding="utf-8"?>
<manifest..>
<application.. android:name="com.orm.SugarApp">
.....
</application>
</manifest>

Entities
The entities need to inherit from SugarRecord including a typed parameter. SugarRecord provides for all the CRUD methods that will be available to the entity classes.

public class Note extends SugarRecord<Note>{
private String title;
private String description;
public Note(Context context){
super(context);
}
...
}

Thats about it. Configuration is done. You’re ready to dive into the sweetness of Sugar. (OK.. I couldn’t stop myself from saying this.)

# inserting values

Note note = new Note(context, "Note 1");
note.save();

# query

Note.findById(context, Note.class, 1);
Note.find(context, Note.class, "title=?", new String[]{"Note 1"});

# delete
Note note = Note.findById(context, Note.class, 1);
note.delete();

# few more..

Note.listAll(context, Note.class);
Note.deleteAll(context, Note.class);

Nice.. All done. Happy Android hacking.

Advertisements

You can’t hide the bitter truth..

Yes. Sooner or later, it would come out.

It leaves you two ways to combat it. One, the cowardly way.. look away from it, don’t share it with people, hide it, punish people for revealing it,  conceal it by any possible means.

Other way is to share it. Share it with all honesty. Show confidence in people.

The second approach gives you all control over the moment, the occasion you reveal the truth. The first one only manages to scare you and makes you repeat the same over and over.

In both cases, you’re unaware of the outcome. But in latter approach, you tend to control better.