Skip to main content

Sugar ORM With Sqlite Android Part I


Sugar ORM  Android Part I:
             If you have came this far in search of how to use an ORM database with your application , you are very much familiar with pain that SQLite querying concept is giving you for all basic CRUD operations with the database.

Sugar ORM is  one of the solution which is available for you to carry out CRUD operation in ease, There is no need to use cursor  for reading from database, Sugar ORM speaks Object with Sqlite database.

Sugar ORM consider a row of data as Object, where SQLite consider it as record.

In this example I am going to show you how to create a table and add data to it using Sugar ORM.

Let's get started.

1. Library Inclusion


First and Foremost thing, add Sugar ORM to your project by adding the following line to your app dependencies.

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

2. Add Database configuration to Application Manifest:


We have to inform the android sdk, that we are using SugarORM to handle CRUD operation with SQLite database by adding the following lines of code to your application android manifest file.

This will also includes the database name that we are about to create and the version of the database.

AndroidManifset.xml:


<application  
     android:allowBackup="true"  
     android:name="com.orm.SugarApp"  
     android:icon="@mipmap/ic_launcher"  
     android:label="@string/app_name"  
     android:supportsRtl="true"  
     android:theme="@style/AppTheme">  
     <meta-data android:name="DATABASE" android:value="codexdatabase.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.example" />  
     <activity android:name=".MainActivity">  
       <intent-filter>  
         <action android:name="android.intent.action.MAIN" />  
         <category android:name="android.intent.category.LAUNCHER" />  
       </intent-filter>  
     </activity>  
   </application>  

In metadata each name and value represent the following.

i. Database - The value you specify here, is name of the Sqlite database you are about to create.
ii. Version -  Database version, like when you add a new table to your project after a release , you have to change this 2 and so on.
iii. Query_log - if this is set to false, you won't  logs in your android monitor , saying whether a new row is inserted using Sugar ORM. This is specially for Programmers.
iv. Domain_Package_name: If you are creating a separate package for keeping your table you, can specify it over here. so that it will be easy for Sugar ORM to keep track of table files.


3. Creating table using Sugar ORM:
      As I have mentioned before, Sugar ORM speaks JAVA with SQLite . To create a Table you have to create a class and extend it with SugarRecord.

Here the Classname (UserTable) represent the table name.
Variables name and profession will be fields for the table.


public class UserTable extends SugarRecord{  
  public String name;  
  public String profession;  
  publice UserTable()
   {
    }
   UserTable(String profile_name,String user_profession)  
   {  
   }  
   public String getName() {  
     return name;  
   }  
   public void setName(String name) {  
     this.name = name;  
   }  
   public String getProfession() {  
     return profession;  
   }  
   public void setProfession(String profession) {  
     this.profession = profession;  
   }  
 }  

As this class extends SugarRecord, a table with the mentioned class with fields will be created when the application was installed on the phone and first opened. So you don't have to worry about how android consider this as a table.

4. Add  records to UserTable:
             To add a row of data to the table you have to create an object matching the following UserTable with two arguments profile_name and user_profession, and you have to call save of method to save the data to the database.


 UserTable user = new UserTable("lingaraj","developer");  
   user.save(); 
 
5.Basic CRUD  Operation with Table:

      To read records from the table all, you have to  create a List with type  UserTable.
List<UserTable> user_list;
      so when an record was read from the table we are going to assign it to this user_list.
 
  Before going to reading record from Table, one good thing to follow is check whether any records exists in the table. This will avoid your application from getting crashed, if there is no record in table but you try to read data from  a table.

So it's always better to start with the count of the table before fetching records from the table.



long count = UserTable.count(UserTable.class);  

 count return type is long here.

if count:
      -1 = Table you are trying to create is not created from the installation, you should check your manifest configuration.
       0 = The table is empty.

i. Get all the records in UserTable:

List<UserTable> user_list;  
long count = UserTable.Count(UserTable.class);
 if(count>0)  
 {  
  user_list = UserTable.listAll(UserTable.class);  
 }  

ii. Querying Entity with Equal to:

  List<UserTable> user_list = new ArrayList<>();
  long count = UserTable.Count(UserTable.class);
  if(count>0)  
  {  
  user_list = UserTable.find(UserTable.class,"name=?","lingaraj");  
  if(user_list==null)  
  {  
    //querying list return empty, there is no record found matching the query.  
  }  
 else  
  {  
   //there are records matching your query.   
  }  
 }  

iii. Querying Entity with Not Equal:

          The following query will return a list of object where the profession is not equal to football.

 List<UserTable> user_list = new ArrayList<>();  
 long count = UserTable.Count(UserTable.class);
 if(count>0)  
  {  
  user_list = UserTable.find(UserTable.class,"profession!=?","football");  
  if(user_list==null)  
  {  
    //querying list return empty, there is no record found matching the query.  
  }  
 else  
  {  
   //there are records matching your query.   
  }  
 }  

iv. Delete Entity from Table:

        Deleting an record from Table involves two things.
First you have to query the record you want to delete and keep it in a list. By default Sugar ORM will create a column named long id, which is attached in each record by default.

We have to use the long id of the record to remove record from the table, in the following manner.


List<UserTable> user_list = new ArrayList<>();  
long count = UserTable.Count(UserTable.class);
if(count>0)
  {  
  user_list = UserTable.find(UserTable.class,"name=?","lingaraj");  
  if(user_list==null)  
  {  
    //querying list return empty, there is no record found matching the query.  
  }  
 else  
  {  
   //User List will have only one record as it looks for name = "lingaraj"
   //Get the id 
   UserTable usertable= UserTable.findById(UserTable.class,user_list.getId());
   usertable.delete();
   //there are records matching your query.   
  }  
 }  


iv.Querying with Boolean Column:

    Let's consider your table have a boolean column named Senior, so how Sugar ORM saves boolean value that you give inside table will be 0 and 1. 0 for false and 1 for true. 

 I have added one more boolean variable to UserTable, which was previously used. 

public UserTable ExampleBoolean extends SugarRecord{  
    String name;  
    String profession;  
    Boolean senior;
    UserTable()
    {
     }
   UserTable(String profile_name,String user_profession, boolean value)  
   {  
     name = profile_name;
     profession = user_profession;
     senior = value;
   }  
   }  

Boolean Query:


List<UserTable> user_list = new ArrayList<>();  
long count = UserTable.Count(UserTable.class);
if(count>0)
  {  
  user_list = UserTable.find(UserTable.class,"senior=?","0");  
  if(user_list==null)  
  {  
    //querying list return empty, there is no record found matching the query.  
  }  
 else  
  {  

   //there are records matching your query.   
  }  
 }  


        
This query will return the objects where senior is false. 

V. Performing Update Operation with Sugar ORM:  

     Updating the record in Sugar ORM was Similar like Delete. Here also you have to query the record which you want to update and keep it a list first. 
      Then using it long id get the record to table object.


       Update the object  and save. 

List<UserTable> user_list = new ArrayList<>();  
long count = UserTable.Count(UserTable.class);
   if(count>0)  
  {  
  user_list = UserTable.find(UserTable.class,"name=?","lingaraj");  
  if(user_list==null)  
  {  
    //querying list return empty, there is no record found matching the query.  
  }  
 else  
  {  
   //User List will have only one record as it looks for name = "lingaraj"
   //Get the id 
   //Update the field of the record lingaraj to codex2android and developer to Blogging
   UserTable usertable= UserTable.findById(UserTable.class,user_list.getId());
   usertable.name = "codex2android"
   usertable.profession = "Blogging"
   usertable.save();
    }  
 }  
     

Comments

  1. Very Nice Post. It helped a lot. Thanks, ooooooh Stop BTW, Sir, where is "Sugar ORM Android Tutorial Part II??

    ReplyDelete
    Replies
    1. happie to help. Forgot to update link on this post . Corrected it.

      Delete
  2. Thanks for shared this information! Have a nice day :D

    ReplyDelete
  3. How and when does Sugar ORM actually create a table?
    Is it when the first record is saved or some other time?

    ReplyDelete
    Replies
    1. Tables are created at the time of app installation, from this line android:name="com.orm.SugarApp" . If you are using singleton class. you should initialize sugarorm inside your onCreate singleton
      Class app extends Application
      {
      public void onCreate()
      {
      SugarContext.init(getApplicationContext());
      }
      }

      Delete
  4. how to change previous table columns in sugar orm after DB is created..? I want to add some new columns in previous table..?

    ReplyDelete
    Replies
    1. At runtime it's not possible to add column to table. But if you are updating your application with the new column for a previous table is possible. Add new column to your table class and increement your db version in manifest.xml like this .
      android:name="VERSION" android:value="2"

      Delete
  5. UserTable usertable= UserTable.findById(UserTable.class,user_list.getId());

    but i am not able to successfully do it.. i am getting error in user_list.getId() . can you guys help me out in that..

    ReplyDelete
    Replies
    1. Me too facing same issue here, I am using compile 'com.github.satyan:sugar:1.5', any solution?

      Delete
    2. ok. wil look into it, can u share the error log with us ?

      Delete
  6. In section

    V. Performing Update Operation with Sugar ORM:

    at line:

    UserTable usertable= UserTable.findById(UserTable.class,user_list.getId());


    getId() method is not available? I mentioned public Long id; filed in domain also.

    ReplyDelete
    Replies
    1. I am using compile 'com.github.satyan:sugar:1.5', any solution for this?

      Delete
    2. can u share the error log of the same.

      Delete
    3. There is no log actually the method getId() is not available as you used in UserTable usertable= UserTable.findById(UserTable.class,user_list.getId());

      Delete
  7. nice blog. excellent post. in this blog stor information of student. in this update, delete,edit perform this opration.

    ReplyDelete
  8. These ways are very simple and very much useful, as a beginner level these helped me a lot thanks fore sharing these kinds of useful and knowledgeable information. Salesforce Training in Chennai | Selenium Training in Chennai

    ReplyDelete
  9. Awesome post.... Just check the spelling mistakes, especially within the code itself.

    ReplyDelete
  10. Wonderful post. I am learning so many things from your blog.keep posting
    PHP Online Training | Pega Online Training | Oracle Soa Online Training

    ReplyDelete
  11. Upgrading database version of Sugar ORM always delete previous table's data.

    ReplyDelete

Post a Comment

Popular posts from this blog

Hiding a Child item(ImageView) In ListView

Download Complete Android Studio Project by  Clicking Here . Important Things About Listview: i.                A List view Recycle it’s view. Meaning If your screen can only fit 5 items. But the total number of item   you are about to display in listview is 100 . ii.               Android won’t load these 100 items into the listview when you set your adapter. iii.             Instead it first load the first five Items on the screen and when you scroll down , it fills the new data into the listview, Which improves performance and Memory. ListView at First Load Item 1   Item 2 Item 3 Item 4 Item 5 ListView When Scrolled Item 3   Item 4 Item 5 Item 6 Item 7 Let’s say you scroll down to view Two more elements item 6 and 7. What happens here is the last two row will be updated with the new value   item 6 and item 7..i.e handled by the adapter

Adding Json array to Serializable Class using Gson.

Why you should use Gson and Serializable Class to Handle Json Data: Gson can be used along with Serializable class to save variables, unnecessary loops and memory  to save the data you get from Json.  Let's Imagine you have array of contact detail and its total count is four. which is something like this. Json Snippet: [ { "name" : "Mark" , "phoneNumber" : "1008788666" , "emailId" : "mark@mail.com" , "address" : "600 Pennsylvania Avenue, Washington DC" }, { "name" : "Christian" , "phoneNumber" : "8007780066" , "emailId" : "christian@mail.com" , "address" : "11 Wall Street New York" }, { "name" : "Benedict" , "phoneNumber" : "4258781555" , "emailId" : "ben