Wednesday, July 01, 2009


Android Database Design Considerations :

There are main two considerations specific to Android that consider when designing database:

A.)  Files (such as bitmaps or audio fi les) are not usually stored within database tables.
Instead, use a string to store a path to the fi le, preferably a fully qualifi ed Content Provider URI.

B.)  While not strictly a requirement, it’s strongly recommended that all tables include an 
auto-increment key fi eld, to function as a unique index value for each row. 
It’s worth noting that if you plan to share your table using a Content Provider, 
this unique ID fi eld is mandatory.

Opening and Creating Databases without the SQLiteHelper:

You can create and open databases without using the SQLiteHelper class with the 
openOrCreateDatabase method on the application Context.

Setting up a database is a two-step process. 

First, call openOrCreateDatabase to create the new data-base. 
Then, call execSQL on the resulting database instance to run the SQL commands that will create 
your tables and their relationships. 

Using the SQLiteOpenHelper:

SQLiteOpenHelper is an abstract class that wraps up the best practice pattern for creating, opening, and upgrading databases. 

By implementing and using an SQLiteOpenHelper, you hide the logic used to decide if a database needs to be created or upgraded before it’s opened.

The code snippet shows how to extend the SQLiteOpenHelper class by overriding the construc-tor, onCreate, and onUpgrade methods to handle the creation of a new database and upgrading to a new version, respectively. 

Example of use of databse in Android Apps. code:

  public MyObject getEntry(long _rowIndex) {
    MyObject objectInstance = new MyObject();
    // TODO Return a cursor to a row from the database and
    // use the values to populate an instance of MyObject
    return objectInstance;
  }
  public int updateEntry(long _rowIndex, MyObject _myObject) {
    String where = KEY_ID + “=” + _rowIndex;
    ContentValues contentValues = new ContentValues();
    // TODO fill in the ContentValue based on the new object
    return db.update(DATABASE_TABLE, contentValues, where, null);
  }

Android and use of Databases:

Plan to create a database adapter, which adds an abstraction layer that encapsulates database inter - actions. It should provide intuitive, strongly typed methods for adding, removing, and updating items. 

A database adapter should also handle queries and wrap creating, opening, and closing the database.

It’s often also used as a convenient location from which to publish static database constants, including table names, column names, and column indexes.