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.
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(); } }
Very Nice Post. It helped a lot. Thanks, ooooooh Stop BTW, Sir, where is "Sugar ORM Android Tutorial Part II??
ReplyDeletehappie to help. Forgot to update link on this post . Corrected it.
DeleteThanks for shared this information! Have a nice day :D
ReplyDeleteHow and when does Sugar ORM actually create a table?
ReplyDeleteIs it when the first record is saved or some other time?
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
DeleteClass app extends Application
{
public void onCreate()
{
SugarContext.init(getApplicationContext());
}
}
how to change previous table columns in sugar orm after DB is created..? I want to add some new columns in previous table..?
ReplyDeleteAt 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 .
Deleteandroid:name="VERSION" android:value="2"
UserTable usertable= UserTable.findById(UserTable.class,user_list.getId());
ReplyDeletebut i am not able to successfully do it.. i am getting error in user_list.getId() . can you guys help me out in that..
Me too facing same issue here, I am using compile 'com.github.satyan:sugar:1.5', any solution?
Deleteok. wil look into it, can u share the error log with us ?
DeleteIn section
ReplyDeleteV. 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.
I am using compile 'com.github.satyan:sugar:1.5', any solution for this?
Deletecan u share the error log of the same.
DeleteThere is no log actually the method getId() is not available as you used in UserTable usertable= UserTable.findById(UserTable.class,user_list.getId());
Deletenice blog
ReplyDeletenice blog. excellent post. in this blog stor information of student. in this update, delete,edit perform this opration.
ReplyDeleteThese 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
ReplyDeleteAwesome post.... Just check the spelling mistakes, especially within the code itself.
ReplyDeletethanks.. will check the spellings as well.
DeleteWonderful post. I am learning so many things from your blog.keep posting
ReplyDeletePHP Online Training | Pega Online Training | Oracle Soa Online Training
Upgrading database version of Sugar ORM always delete previous table's data.
ReplyDeleteIt is very excellent blog and useful article thank you for sharing with us, keep posting.
ReplyDeletec Software Testing Training in Chennai | Software Testing Training in Anna Nagar | Software Testing Training in OMR | Software Testing Training in Porur | Software Testing Training in Tambaram | Software Testing Training in Velachery
Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
ReplyDeleteJava training in Chennai
Java Online training in Chennai
Java Course in Chennai
Best JAVA Training Institutes in Chennai
Java training in Bangalore
Java training in Hyderabad
Java Training in Coimbatore
Java Training
Java Online Training