Skip to main content

Sugar ORM SQlite Android Part 2


Code Walkthrough :

      Previously you have seen how to use SugarORM with Android . In this , I will be giving you a walkthrough how the whole code works in an application, with a sample application which I have created. 

you can also download the complete android studio project from here

AndroidManifest.xml:

This is how the sample application will look like, when the application get installed, android will create an sqlite database named codexandroid.db as mentioned in this manifest. 

It will also assign the database version to be 1, if you add more table to your database you have to increement your database version number before deploying it on Google play store or for demo.

android:noHistory="true"  --> This is to stop android from keeping activity in stack , so that when you press back in this application, you won't be taken back to the previously used activity. 


    <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="codexandroid.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.hourglass.lingaraj.sugarormtuts.database" />

        <activity android:name=".Home">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".AddDataToTable" android:noHistory="true"/>
        <activity android:name=".ViewTableData" android:noHistory="true"/>
        <activity android:name=".UpdateTableData" android:noHistory="true"/>
        <activity android:name=".DeleteTableData" android:noHistory="true"/>

    </application>

UserTableSugar.java:

      A table name USER_TABLE_SUGAR will be created with the structure mentioned below.
     i. Member variable and methods must be static so that you can access it outside it's class scope. 
     ii. Empty Constructor is a must. 


public class UserTableSugar extends SugarRecord {

    public String name;
    public String profession;
    public boolean senior;

    public UserTableSugar()
    {

    }

   public UserTableSugar(String person_name,String profess,boolean value)
    {
        this.name = person_name;
        this.profession = profess;
        this.senior = value;
    }

}



AddDataToTable.java:

   In this class you will be adding new data to your table. I have commented inside code, so that you can understand easily, rather than explaining, it here. 

public class AddDataToTable extends AppCompatActivity {
    private Button submit,clear;
    private EditText name,profession,senior;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_data);
        initialDeclaration();
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /* If submit button is pressed, this listener will be triggered, and get Text from each fields and right it to database.
                 *
                 */
                String temp_name = name.getText().toString();
                String temp_profession = profession.getText().toString();
                String temp_senior = senior.getText().toString();
                boolean value;
                if (temp_senior.equals("true")) {
                    value = true;
                } else if (temp_senior.equals("false")) {
                    value = false;
                } else {
                    value = false;
                }
                //Passing data to Table using Constructor which we have Created  inside UserTableSugar.java
                UserTableSugar userTable = new UserTableSugar(temp_name, temp_profession, value);
                userTable.save();
                //calling save will write the data in UserTableSugar.java variable to SQLite Table
                clearAllFields();
                Toast.makeText(getApplicationContext(), "Data added to Table", Toast.LENGTH_SHORT).show();

            }
        });

        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearAllFields();
            }
        });

    }

    private void clearAllFields() {

        name.setText("");
        profession.setText("");
        senior.setText("");
    }

    private void initialDeclaration() {
        name = (EditText) findViewById(R.id.name_edittext);
        profession = (EditText) findViewById(R.id.professsion_editText);
        senior = (EditText) findViewById(R.id.senior_editText);
        submit =(Button) findViewById(R.id.submit);
        clear = (Button) findViewById(R.id.clear);


    }
}


UpdateTableData.java:


public class UpdateTableData extends AppCompatActivity {

    EditText update_name,update_profession,update_senior,searchNameEditText;
    Button search,update;
    List<UserTableSugar> userTable;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_update_layout);
        searchNameEditText = (EditText) findViewById(R.id.name_edittext);
        search = (Button) findViewById(R.id.search);
        update = (Button) findViewById(R.id.update);
        update_name = (EditText) findViewById(R.id.update_name);
        update_profession = (EditText) findViewById(R.id.update_profession);
        update_senior =  (EditText) findViewById(R.id.update_senior);

        /* Here we are searching by name from table, when you enter a name and press search , it will fetch the particular row,
         * and display in editText field, after changing the data you can save it with update code return below.
         */


        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(searchNameEditText.getText().toString().isEmpty())
                {
                    Toast.makeText(getApplicationContext(),"Enter a name to search",Toast.LENGTH_SHORT).show();
                }
                else
                {
                   long count = UserTableSugar.count(UserTableSugar.class);
                    if(count>0)
                    {
                        userTable = UserTableSugar.find(UserTableSugar.class,"name=?",searchNameEditText.getText().toString());
                        if(userTable==null)
                        {
                            Toast.makeText(getApplicationContext(),"No matching Record found",Toast.LENGTH_SHORT).show();
                        }
                        else
                        {
                            update_name.setText(userTable.get(0).name);
                            update_profession.setText(userTable.get(0).profession);
                            update_senior.setText(String.valueOf(userTable.get(0).senior));
                        }
                    }
                }

            }
        });


        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(update_name.getText().toString().isEmpty() || update_profession.getText().toString().isEmpty() || update_senior.getText().toString().isEmpty())
                {
                    Toast.makeText(getApplicationContext(),"Any of the three fields should not be empty",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    //Code to update User data on Table.
                    UserTableSugar userTableSugar = UserTableSugar.findById(UserTableSugar.class,userTable.get(0).getId());
                    userTableSugar.name =  update_name.getText().toString();
                    userTableSugar.profession = update_profession.getText().toString();
                    boolean value;
                    if(update_senior.getText().toString().equals("true") ||update_senior.getText().toString().equals("false"))
                    {
                        value = Boolean.valueOf(update_senior.getText().toString());
                    }
                    else
                    {
                        value = false;
                    }

                    userTableSugar.senior = value;
                    Toast.makeText(getApplicationContext(),"Table Data Updated",Toast.LENGTH_SHORT).show();

                    clearFields();
                    userTableSugar.save();
                }

              }
        });



    }

    private void clearFields() {
        update_name.setText("");
        update_profession.setText("");
        update_senior.setText("");
    }
}

ViewTableData.java


public class ViewTableData extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_data);
        ListView listView = (ListView) findViewById(R.id.list_view);
        long count = UserTableSugar.count(UserTableSugar.class);
        if(count>0)
        {
               /* Get all records in table and display in listview, where a button available for for deleting.
             *
            * */

            UserTableSugar.listAll(UserTableSugar.class);
            List<UserTableSugar> userTable = UserTableSugar.listAll(UserTableSugar.class);
            CustomAdapterListview madapter = new CustomAdapterListview(getApplicationContext(),userTable);
            listView.setAdapter(madapter);
        }
        else
        {
            Toast.makeText(getApplicationContext(), "No Data Available in Table", Toast.LENGTH_LONG);

        }

    }

    }

DeleteTableData.java


public class DeleteTableData extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delete_data);

        ListView listView = (ListView) findViewById(R.id.list_view);
        long count = UserTableSugar.count(UserTableSugar.class);
        if(count>0)
        {
            /* Get all records in table and display in listview, where a button available for for deleting. on pressing it the
             * particular row will be removed from Table.
            * */
            List<UserTableSugar> userTable = UserTableSugar.listAll(UserTableSugar.class);
            CustomAdapterListviewDelete madapter = new CustomAdapterListviewDelete(getApplicationContext(),userTable);
            listView.setAdapter(madapter);
        }
        else
        {
            Toast.makeText(getApplicationContext(), "No Data Available in Table", Toast.LENGTH_LONG);

       }
    }
}

Hope it helps.. 

Comments

  1. Thanks for every other informative site. The place else may just I get that kind of information written in such an ideal means? I have a venture that I’m just now operating on, and I have been on the look out for such information. this

    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

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