Android Sugar ORM Database

In this android tutorial, we are going to learn how to us android Sugar ORM database in our android project. If you have not used Sugar ORM, you will not understand how easy and concise it is.

Android Sugar ORM library is an object relational mapping library that create and simplifies the interaction with SQLite database in Android.

I have written tutorials on different topics related to android database and libraries, you can check them out below to see the one that wets your appetite.

1. Android SQLite Database Example Tutorial.

2. Android Realm Database Example Tutorial.

3. Android SQLBrite Database Example Tutorial.

Why do you need Sugar ORM

I know the question that we be in your mind now is why do we still need Android Sugar ORM?

1. It eliminates writing SQL queries to interact with SQLite db.

2. It takes care of creating your database.

3. It manages object relationships too.

4. It provides you with clear and simple APIs for db operations

How to use Sugar ORM database?

Don’t be so tense about learning how to use Sugar ORM because by the time you start you will realized that you have already finished it. If you want to read more about Android Sugar ORM, you can look up the Introduction to Android Sugar ORM 

To test this library, we are going to create a simple android app using the RecyclerView widget. It will display categories and each category will contain a single image and a text.

To create a Sugar ORM Entity you must extend the SugarRecord class. A simple example is from Sugar ORM documentation.

public class Book extends SugarRecord
public class Book extends SugarRecord {
    String title;
    String edition;
    public Book(){
    public Book(String title, String edition){
        this.title = title;
        this.edition = edition;


Book book = new Book("Title here", "2nd edition");


Book book = Book.findById(Book.class, 1);


Book book = Book.findById(Book.class, 1);
book.title = "updated title here"; 
book.edition = "3rd edition";;


Book book = Book.findById(Book.class, 1);

Bulk Retrieval

List<Book> books = Book.listAll(Book.class);

What we will create in this tutorial

In other to get a visual understanding of what we are going to create in this android tutorial, I have add below some screen shots from the application.

android sugar orm

Create New Android Project

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 10

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 25

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidSugarORM

Package: com.inducesmile.androidsugarorm

Select Empty Activity

Name your activity: MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

Build.gradle Dependency

First, we are going to add Sugar ORM android library to our application. This will help use to access and make use of classes and methods in Sugar ORM.

Add the line to your build.gradle app level file as shown below.

compile 'com.github.satyan:sugar:1.4'

The complete code for the build.gradle file is shown below

apply plugin: ''
android {
    compileSdkVersion 25
    buildToolsVersion "24.0.1"
    defaultConfig {
        applicationId "com.inducesmile.androidgreenorm"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner ""
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), ''
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('', {
        exclude group: '', module: 'support-annotations'
    compile ''
    compile ''
    compile ''
    compile 'com.github.satyan:sugar:1.4'
    testCompile 'junit:junit:4.12'


There are few configuration changes to make in AndroidManifest.xml file. We need to change the application name to android:name=“com.orm.SugarApp”

Thereafter, add the following meta-data inside the application element.

<meta-data android:name="DATABASE" android:value="notes.db" />
<meta-data android:name="VERSION" android:value="1" />
<meta-data android:name="QUERY_LOG" android:value="true" />
<meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="com.inducesmile.androidgreenorm" />

The complete code for AndroidManifest.xml is shown below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
        <meta-data android:name="DATABASE" android:value="notes.db" />
        <meta-data android:name="VERSION" android:value="1" />
        <meta-data android:name="QUERY_LOG" android:value="true" />
        <meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="com.inducesmile.androidgreenorm" />
        <activity android:name=".MainActivity">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />


We are going to update our project strings.xml file located in the values folder inside the res folder. Open the file and add the code below to it.

    <string name="app_name">Android Sugar ORM</string>
    <string name="pizza">Pizza</string>


Open the colors.xml file in the same location as the strings.xml file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>


Open the main layout file and add the code below.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
        android:scrollbars="none" />

Create an adapter class for RecyclerView. Name the created java class Open this class and add the code below.

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
public class CategoryAdapter extends RecyclerView.Adapter<CategoryViewHolder>{
    private Context context;
    private List<ImageSugarPojo> categoryObject;
    public CategoryAdapter(Context context, List<ImageSugarPojo> categoryObject) {
        this.context = context;
        this.categoryObject = categoryObject;
    public CategoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_category_list, parent, false);
        return new CategoryViewHolder(layoutView);
    public void onBindViewHolder(CategoryViewHolder holder, int position) {
        final ImageSugarPojo catObject = categoryObject.get(position);
        int resId = getResourseId(context, "drawable", catObject.getImage(), context.getPackageName());
    public int getItemCount() {
        return categoryObject.size();
    public static int getResourseId(Context context, String pVariableName, String pResourcename, String pPackageName) throws RuntimeException {
        try {
            return context.getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
        } catch (Exception e) {
            throw new RuntimeException("Error getting Resource ID.", e);

Create a new class and name it Open this class and add the code below to it.

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class CategoryViewHolder extends RecyclerView.ViewHolder{
    public TextView categoryName;
    public ImageView categoryImage;
    public View mItemView;
    public CategoryViewHolder(View itemView) {
        mItemView = itemView;
        categoryName = (TextView)itemView.findViewById(;
        categoryImage = (ImageView)itemView.findViewById(;


We will create a layout file for RecyclerView list item. It will contain an ImageView and a TextView. Name the layout file menu_category_list.xml. Open this layout file and add the code below.

<LinearLayout xmlns:android=""
           android:src="@drawable/sandals" />
           android:textStyle="bold" />

Now this is where the magic happens. We are going to create our database object. This class will inherit from the SugarRecord class. Create a new java class file and name it CategoryPojo.

Open the file and add the code below.

import com.orm.SugarRecord;
public class CategoryPojo extends SugarRecord{
    private String image;
    private String text;
    public CategoryPojo(){}
    public CategoryPojo(String image, String text){
        this.image =image;
        this.text = text;
    public String getImage() {
        return image;
    public void setImage(String image) {
        image = image;
    public String getText() {
        return text;
    public void setText(String text) {
        this.text = text;

Open the MainActivity class and add the code below.

import android.os.Bundle;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private CategoryPojo categoryPojo;
    protected void onCreate(Bundle savedInstanceState) {
        recyclerView = (RecyclerView)findViewById(;
        GridLayoutManager mGrid = new GridLayoutManager(this, 2);
        List<CategoryPojo> imageSugar = CategoryPojo.listAll(CategoryPojo.class);
        CategoryAdapter mAdapter = new CategoryAdapter(this, imageSugar);

This brings us to the end of this tutorial. I hope that you have learn something. Run your app and see for yourself.

You can download the code for this tutorial above. If you are having hard time downloading the tutorial, kindly contact me.

Remember to subscribe with your email address to be among the first to receive my new android blog post once it is published.


  1. Avatar
    • Inducesmile

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

50% Discounts On Projects

Do you have a custom project with a clear requirements, we are currently giving a 50% discount on all projects.

We will work with you to ensure we deliver what you need.

If you have questions or want to chat with us, you can reach us on Skype (henry.tochi)

Languages and technologies we use - Java, Kotlin, Laravel, Vue, React, Flutter, Swift and more.