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;
    }
}

 Save

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

Retrieve

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

Update

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

Delete

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

Bulk Retrieval

List<Book> books = Book.listAll(Book.class);
Book.deleteAll(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: 'com.android.application'
android {
    compileSdkVersion 25
    buildToolsVersion "24.0.1"
    defaultConfig {
        applicationId "com.inducesmile.androidgreenorm"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    compile 'com.android.support:appcompat-v7:25.0.1'
    compile 'com.android.support:recyclerview-v7:25.0.1'
    compile 'com.github.satyan:sugar:1.4'
    testCompile 'junit:junit:4.12'
}

 AndroidManifest.xml

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="http://schemas.android.com/apk/res/android"
    package="com.inducesmile.androidgreenorm">
    <application
        android:name="com.orm.SugarApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <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">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

 Strings.xml

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.

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

 Colors.xml

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"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

 axtivity_main.xml

Open the main layout file and add the code below.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.inducesmile.androidgreenorm.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/category_menu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:scrollbars="none" />
</RelativeLayout>

 CategoryAdapter.java

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

import android.content.Context;
import android.support.v7.widget.RecyclerView;
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;
    }
    @Override
    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);
    }
    @Override
    public void onBindViewHolder(CategoryViewHolder holder, int position) {
        final ImageSugarPojo catObject = categoryObject.get(position);
        holder.categoryName.setText(catObject.getText());
        int resId = getResourseId(context, "drawable", catObject.getImage(), context.getPackageName());
    }
    @Override
    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);
        }
    }
}

CategoryViewHolder.java

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

import android.support.v7.widget.RecyclerView;
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) {
        super(itemView);
        mItemView = itemView;
        categoryName = (TextView)itemView.findViewById(R.id.category_name);
        categoryImage = (ImageView)itemView.findViewById(R.id.category_image);
    }
}

menu_category_list.xml

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="http://schemas.android.com/apk/res/android"
       xmlns:card_view="http://schemas.android.com/apk/res-auto"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginBottom="4dp"
       android:layout_marginTop="4dp"
       android:gravity="center"
       android:orientation="vertical"
       android:padding="8dp">
       <ImageView
           android:id="@+id/category_image"
           android:layout_width="200dp"
           android:layout_height="150dp"
           android:adjustViewBounds="true"
           android:contentDescription="@string/app_name"
           android:src="@drawable/sandals" />
       <TextView
           android:id="@+id/category_name"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginTop="10dp"
           android:text="@string/pizza"
           android:textColor="@color/colorPrimaryDark"
           android:textSize="14dp"
           android:textStyle="bold" />
   </LinearLayout>

CategoryPojo.java

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;
    }
}

MainActivity.java

Open the MainActivity class and add the code below.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private CategoryPojo categoryPojo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        categoryPojo.setImage("bulgar");
        categoryPojo.setText("Bulgar");
        categoryPojo.save();
        recyclerView = (RecyclerView)findViewById(R.id.category_menu);
        GridLayoutManager mGrid = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(mGrid);
        recyclerView.setHasFixedSize(true);
        List<CategoryPojo> imageSugar = CategoryPojo.listAll(CategoryPojo.class);
        CategoryAdapter mAdapter = new CategoryAdapter(this, imageSugar);
        recyclerView.setAdapter(mAdapter);
    }
}

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.

OTHER INTERESTING POSTS:

2 Comments

Add a Comment