Tuesday, May 07, 2013

How to use SQLite Db in the Android Development


SQLite is a self-contained i.e., having all the modules and dependencies with in it & does not depend much on external libraries. This is one of the important reasons why most of the embedded devices use SQLite as temporary storage. Well-known examples are Google, Mozilla Firefox, Apple, Adobe and Android devices. It has zero-configuration with out any separate process for installation or configuration.

Android has 2 main packages, which lets us to use SQLite in the application. android.database and android.database.sqllite has all the necessary api's for create/read/update and delete actions.
Also SQLiteOpenHelper class provides public methods like onCreate, onUpgrade, onOpen methods. onCreate is called whenever the database is created for first time, onOpen when the DB has been opened and onUpgrade when the databased needs to be upgraded.

A database handler class which implements the SQLiteOpenHelper should call the constructor to create helper object to create, open or manage database. Constructor takes database name & database version. See below.

public SQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version)

As a first step to implement SQLite, the database handler class should extend SQLiteOpenHelper. In the constructor method call the super() method by passing the context, database name and version.

         public DatabaseHandler(Context context) {
             super(context, DATABASE_NAME, null, DATABASE_VERSION);
         }

Database handler class should also implement the onCreate & onUpgrade methods. onCreate method is called by framework when the DB is created for the first time and onUpgrade method is used whenever DB tables need to be updated.
ex:
         public void onCreate(SQLiteDatabase db) {
                  // Category table create query
                  String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
                  db.execSQL(CREATE_CATEGORIES_TABLE);
         }

// Upgrading database
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                  // Drop older table if existed
                  db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
                  // Create tables again
                  onCreate(db);
         }

For any read/write operation, SQLiteOpenHelper class provides getReadableDatabase() & getWritableDatabase() respectively. These methods returns reference to SQLiteDatabase object which can be used to create, read, update and delete from tables. For ex, below example shows Create/Open database.

         SQLiteDatabase db = this.getReadableDatabase();

         // Create/open a database for read/write operation.
         SQLiteDatabase db = this.getWritableDatabase();

The db object returned from the getReadableDatabase & getWritableDatabase provides create(), insert(), delete(), update() methods.
         Ex: insert takes table name, optional null column and content values that need to be inserted into the table.
         // Inserting Row
                  db.insert(TABLE_LABELS, null, values);

We can write query in 2 ways, First is raw query like "select * from ", "insert into" etc. and second one is structured query. For this SQLiteDatabase provides 2 methods query() & rawQuery().

query() methods provides structured interface which takes table name, array of columns that needs to be fetched, filter column (for WHERE clause), groupBy, orderBy, having and limit. Example below.

         db.query(TABLE_NAME, String[] columnNames, String[] selection, group by, having, order by);

rawQuery() takes the raw sql just like any sql database. ex
         db.rawQuery("select * from TABLE_NAME", null);

Both query() & rawQuery() returns something called Cursor object. Cursor is not actual result set; rather it is an object that is positioned before the first row of the result set. The handler class should iterate through the cursor object to get through all rows.
ex:
                  Cursor cursor = db.rawQuery(selectQuery, null);
                  // Looping through all rows and adding to list
                  if (cursor.moveToFirst()) {
                           do {
                                    cursor.getString(1);
                           } while (cursor.moveToNext());
                  }
Cursor.get*(), methods are the way to access columns of each rows.

All the above methods insert(), read(), delete() etc. should implement close() method to close db & cursor operations.

                  // closing connection
                  cursor.close();
                  db.close();

Reference materials:

Friday, April 19, 2013

CSS Specificity

Many times wondered in which order the styles are applied to document elements. When you are working on a bigger project or old projects which was written by ex-developers (no offense here) wondered how to over write a particular style or write a style so it has the higher precedence over other style.
We have more ways to add styles to a documents inline Style & external Style both containing

  •  Id (#) selector, 
  • class (.) selector, 
  • attribute selector (input[type=password]),
  • pseudo-classes (:link, :hover:, :visited, :focus, :active) , 
  • pseudo-elements (:before, :after, :first-line, :first-letter, :first-child)


All the above mentioned style have a rating/priority which is used while style the document.
ex: As we know  Id (#) selector has precedence over any other selection since ID is unique in a document and obviously they have the highest rating. Any style (inline or external) given using the ID is considered before class, pseudo elements.
ie, with inline style like below

  1. <style> #test {  text-decoration:"line-through"; }</style> 
  2. <a id="test" style="text-decoration:line-through;">Test</a>

has the higher specificity that any other style given to the above element.
similarly while considering external stylesheet, the first style (1) has the higher specificity that (2).

Example 1- a#test {  text-decoration:"line-through"; }
Example 2-  a[id=test] { text-decoration:"none"; }

How is the specificity calculated.
  1. # (id) selector takes 100 points 
  2. . (class, attribute, pseudo) selectors take 10 points
  3. type selector, pseudo-element selector take 1 points.
Considering the above example (1 & 2) we can easily say that example 1 style is always selected over example 2. Having said that, there is always some thing beyond the above 3. That is the inline style. Irrespective of any thing, the style attribute takes higher precedence/specificity over any thing (ie it has value 1000 points).