Thursday, 13 June 2013

To Do\Shopping List



Introduction  
This tip shows how a Shopping\To do list application is created. It gives an idea of the following:
  1. Adding a list Item in Application.
  2. Opening Dialog from Android Activity.
  3. Working with SQlite. 
  4. How to return data from one activity to another.
In this tip we would be discussing about the 3rd points. The first two pints are discussed here.   

Using the code
Working with SQLite  

SQLite
A software library that implements a SQL database engine. It is fast and lightweight. Hence, best for Mobile devices. The database is stored within a single file. Every android application can have its own private database. It is being used by many well-known groups/brands like Adobe, Airbus, Apple, Dropbox, General Electric, Google, Intuit, McAfee, Microsoft, php, python, skype, Toshiba etc. 

Database Fundamentals
Database is a collection of structured data organized in the form of tables. Table contains columns to define the attribures of data and rows contain the data records. We can inspect and manipulate database data especially in 4 ways:
Add – using
INSERT Command
Delete - using
DELETE Command
Modify - using
UPDATE Command
View – using
SELECT Command 

Using SQLite in Android   
Android provides us few classes, which can be used while communicating with SQLite: 
  1. SQLiteOpenHelper 
  2. SQLitedatabase 
  3. Cursor
Steps:
  1. Derive a helper class from SQLiteOpenHelper.  
  2. Override OnCreate method and write query for creating the database and its schema.  
  3. In the helper class, write methods for the following :  
    • Inserting new records 
    • Deleting records  
    • Updating records.  
    • Reading Records.  
Its Done !!!  

Here, In this examples, we are using one table (NoteTable) with 4 columns  (Note id, date/time, name and content)    
Sample Query for onCreate method for Creating database schema. 
 String sCreateSQL = "CREATE TABLE IF NOT EXISTS " + CommonClass.TABLE_NAME + "( " + CommonClass.COL_SRNO
                + " INTEGER PRIMARY KEY, " + CommonClass.COL_DATETIME + " TEXT, "
                + CommonClass.COL_NOTENAME + " TEXT, " + CommonClass.COL_NOTECONTENT + " TEXT )";
        db.execSQL(sCreateSQL);
db is an object of type SQLiteDatabase , which is passed as a parameter in onCreate function.
For preforming any of the operations on data (like insert, update, delete), we need to get an object of SQLiteDatabase. In the derived helper class, by using this object we can call either getWritableDatabase or getReadabledatabase (depending on our requirement) for getting the database object.
Insert\Update\Delete Records: 
  1. Get the database object using getWritableDatabase.
  2. Use ContentValues for adding data corresponding to the columns.
  3. Execute using insert\update\delete function. 
  4. Dont forget to close the database. 
Sample Code:    
SQLiteDatabase db = this.getWritableDatabase();  //get database Object

//Use contentValues for Insert and update
ContentValues contentvalue = new ContentValues();
contentvalue.put(CommonClass.COL_DATETIME, objShoWData.get_DateTime());
contentvalue.put(CommonClass.COL_NOTECONTENT, objShoWData.get_NoteData());
contentvalue.put(CommonClass.COL_NOTENAME, objShoWData.get_NoteName());
db.insert(CommonClass.TABLE_NAME, null, contentvalue);

OR    

db.update(CommonClass.TABLE_NAME, contentvalue, CommonClass.COL_SRNO + " = ?",
new String[] { String.valueOf(objShowdata.get_NoteId()) });
OR
db.delete(CommonClass.TABLE_NAME, CommonClass.COL_SRNO + " = ?",
new String[] { String.valueOf(nId) });
db.close(); //Close database

View Existing records:
  1. Get the database object using getReadableDatabase.   
  2. Write the SELECT statement.   
  3. Use rawQuery function to execute the SELECT Query.  
  4. Iterate the cursor object returned by the rawQuery function. 
  5. Retreive values using getString and getInt etc.
  6. Dont forget to close the database. 
It's done!!!   

SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

if (cursor.moveToFirst()) {
do {
    ShowData objShowData = new ShowData();
    objShowData.set_NoteId(cursor.getInt(0));
    objShowData.set_DateTime(cursor.getString(1));
...  ... //Read values from cursor....
    listShowData.add(objShowData);
    } while (cursor.moveToNext());
}
db.close();

Sunday, 9 June 2013

Introduction

This article shows how a Shopping\To do list application is created. It gives an idea of the following:
  1. Adding a list Item in an Activity
  2. Opening Dialog from Android Activity.
  3. Working with SQlite
  4. How to return data from one activity to another
In this article we will be discussing about the first 2 points.

The Beginning

This article assumes that you are aware, how an android project is created.
Create a new Android Project with the following details:
Application Name = UtilityPlus Project Name = UtilityPlus Package Name = com.utility.utilityplus
Minimum Required SDK & Target SDK = API 11 Android 3.0 (HoneyComb) and Click Finish.

Activities & Resources:
 
This application contains the following major components:
  1. MainActivity - Displaying the list of existing Shopping\To do List
  2. Dialog - A pop-up asking for the name of list from user
  3. Add new Data Activity - User would enter the content of list here.
  4. Adapter - For display of Data in MainActivity
  5. DatabaseHelper - For connecting and communicating with MainApplication.

Adding a list item in an activity 

Before moving on, we need to understand a few basic concepts, which are being used here:

ListView - Displays a scrollable list of logically related items. Its an important UI Component and is used in many apps for various purposes.

ListView Item - The items\data being displayed in a single row. It can be plain text(E.g. displaying the names of your contacts) or it can be much more complicated with 2 EditText for name and number, 2 button for edit and delete.

Data Source - The web definition of DataSources say : "The people, documents, products, activities, events and records from which data are obtained." [Reference: http://www.evaluationtoolkit.org/glossary]
With respect to coding it can be an ArrayList, Array of any data-type (basic or complex)

Adapter - A piece of code, which takes data from a data-source and makes it compatible to the ListView.

In practical the relationship between ListView and its adapter is much more complicated.

Display plain text as a List Item in The ListView

1. Add ListView in the resource layout XML.
2. Create\find a Data Source.
3. Create an Adapter for a Data Source.
4. Assign Adapter to the ListView.
Its Done

The ListView can be dragged from the left pane of the graphical display of the Resource XML or the below code can be copied in the XML view.
 
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" 
></ListView>
 
Data Source: Here, we are taking an Array of String

String[] strNoData = { "Item1", "Item2", "Item3" };//DataSource

Adapter: We are using simple arrayAdapter and then set adapter in the  listview using setAdapter.
 
ArrayAdapter<string> objAdapter = new ArrayAdapter<string>(this,
     android.R.layout.simple_list_item_1, android.R.id.text1,
     strDataSource);
listview.setAdapter(objAdapter);</string> </string> 

Display set of controls as a List Item in The ListView

Steps:
1. Add ListView in the resource layout XML.
2. Create\find a Data Source.
3. Create an XML layout resource for the row template in ListView
4. Create an Adapter for a Data Source.
5. Assign Adapter to the ListView.
Its Done !!!

XML layout resource for the row template in ListView. The below template would be used for all the rows in the ListView.
 
<LinearLayout ...
         <FrameLayout  ...
        <TextView android:id="@+id/textView_datetime" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="" 
        android:textAppearance="?android:attr/textAppearanceMedium" 
        android:layout_gravity="left"/>
        <Button android:id="@+id/button_Edit" android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="@+string/str_edit" android:onClick="onClick"
        android:layout_gravity="center_horizontal"/>
        <Button android:id="@+id/button_delete" 
        android:layout_height="wrap_content" 
        android:layout_width="wrap_content" 
        android:text="@+string/str_delete" 
        android:layout_gravity="right" 
        android:onClick="onClick"/>
        </FrameLayout>
        <TextView android:id="@+id/textView_notename" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="" android:textAppearance="?android:attr/textAppearanceMedium" 
        android:gravity="bottom"/>
</LinearLayout> 

Creating a custom adapter
We can extend any adapter class provided by Android and can create our own custom adapter. Here, we would be using ArrayAdapter class. In the adapters we need to override getView method.This method would return the view of single row. See the code below:
 
@Override
public View getView(int position, View convertView, ViewGroup parent) {        
     LayoutInflater vi = (LayoutInflater)getContext().
            getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     convertView = vi.inflate(R.layout.showlistrow, null);
            
     ShowData showData = m_ListItems.get(position);
            
     if (showData != null) {
     try {
        //Write code to display the controls in the layout xml
        } catch (Exception ex) {
          ...
       } }
        return convertView;
    }
 
The above code is correct but we can optimize it further. We can reuse the Views of List Items which are not visible on the screen. Lets suppose , 5 List Items can be displayed on the screen. We would create new view for each item. Right now, there are 5 views in the memory. When we scroll down our List Item the First List Item is not being displayed and 6th comes in the view. So, instead of creating a new view for the 6th item , we can reuse the first items view. Creating a new view in Android is expensive Just add a check for existing view.
 
@Override
public View getView(int position, View convertView, ViewGroup parent) {        
if(convertView!=null) { //Check added for optimizing the code.
            LayoutInflater vi = (LayoutInflater) 
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.showlistrow, null);
            
            ShowData showData = m_ListItems.get(position);
            
            if (showData != null) {
                try {
                    //Write code to display the controls in the layout xml
                } catch (Exception ex) {
                    ...
                }
            }
            return convertView;
    }

Assign adapter to ListView
 
ShowDataAdapter adapter_Data = new ShowDataAdapter(this,
               android.R.layout.simple_list_item_1, 
               android.R.id.text1,list_AdapterItems);
listview.setAdapter(adapter_Data);

Opening Dialog from Android Activity

This can be achieved in 2 ways

1. Via AlertDialog
2. Via Dialog Class

Via AlertDialog

1. Declare AlertDialog Object.
2. Set Message and Title.
3. Set Positive and Negative Buttons.
4. Show Dialog.
 
AlertDialog alertDialog = new AlertDialog.Builder(Main.this).create();
alertDialog.setTitle("Error...");
alertDialog.setMessage("Unable to open. Continue?");
alertDialog.setPositiveButton(/*Create new onclickListener*/);
alertDialog.setNegativeButton(/*Create new onclickListener*/);
alertDialog.show();

Via Dialog Class

Steps
1. Create an XML Resource for Dialog Layout.
2. Derive a class from android.app.Dialog Class of Android.

In the XML Resource add all the controls that we want to display in our Dialog. Here, we would be adding a TextView and OK, Cancel buttons. In the constructor of derive class, set XML Resource by calling setContentView().
 
setContentView(R.layout.popup);

Revision History

9th June 2013 Initial Release