Archive

Posts Tagged ‘tutorial’

Getting started: Sqlite on Android

October 12, 2011 Leave a comment

I am writing this tutorial with some hesitation, i really don’t want to make another copy of this android SQLite tutorial That is wondering around the net. So this tutorial is a part or a series, after this “getting started” one, a more interesting one on how to implement some design patterns to work with your application and SQLite database.

Building a Database on an android system is not a very pleasant job but from some point of view it has its advantages. If you have worked with a database element manager like phpmyadmin visual studio or any other, you know its the easiest way to build a database, easy to modify and see the big picture, your able to insert data and edit the database content easily and the most important… it saves TIME. With sqlite on android you do not really have any way of visualizing your database, you will need to create it when your application runs for the first time. Thous who love the scripting business will disagree with me. I personally like getting things done (when i am not trying to study how things work and gain experience). However the idea of having all of your code (as well as the databases) in the same place is a good practice and simplifys things when developing.

Note: There are some ways of visualizing and edit your database with an external editor and inject it into your application but its not what this tutorial will be about. here we will see how to create a database for the android system use the method “GOD” intended. Then we will see how we can go about simplifying the solution so we will have a good and robust code what will be easy to manage and enlarge.

Lets create our Chocolate Database.
What were going to do is build a wrapper class that will extend SQLiteOpenHelper (A helper class for managing database creation and version management.). It will hold all the code necessary to create, delete, update and maintain the Database.

public class ChocolateDbHelper extends SQLiteOpenHelper {

public static final int dbVersion = 1; //dbVersion is used by SQLiteOpenHelper to know if an upgrade/downgrade is needed for the existing db

public static final string CHOCOLATE_TABLE_NAME = “chocolate_table”; public static final string CHOCOLATE_ID_COL = “chocolate_id”; public static final string CHOCOLATE_TYPE_COL = “chocolate_type”; public static final string CHOCOLATE_QUANTITY_COL = “chocolate_quantity”;

public static String dbCreateString = “CREATE TABLE ” + CHOCOLATE_TABLE_NAME  + ” ( ” + CHOCOLATE_ID_COL  + ” INTEGER PRIMARY KEY AUTOINCREMENT, ” + CHOCOLATE_TYPE_COL + ” INTEGER NOT NULL, ” + CHOCOLATE_QUANTITY_COL + ” REAL)” ;

public ChocolateDbHelper (Context context) {

super(context, dbName , null, dbVersion);

 }

@override
public void onCreate(SQLiteDatabase db) {

try{

db.execSQL(dbCreateString);

} catch (SQLException e) {

//throw some logs here.

}

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

try {

db.execSQL(“DROP TABLE IF EXISTS ” + CHOCOLATE_TABLE_NAME ); onCreate(db);

} catch (SQLException e) {

//produce some logs here

}

}

public long EnterNewChocolate(Chocolate chocolate) {

SQLiteDatabase db = null; long rowId = -1; try {

db = this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(CHOCOLATE_TYPE_COL , chocolate.getChocolateType()); cv.put(CHOCOLATE_QUANTITY_COL , chocolate.getQuantity()); rowId = db.insert(CHOCOLATE_TABLE_NAME , null, cv);

} finally {
return rowId;
}

}

About onCreate(SQLiteDatabase db):

This function will be called when the database is created for the first time.
The creation of tables/triggers and population of the database should happen here.

Variables:
db – The database.

About onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion):

This function is called when the version of the database has changed to grater than the previous version (there’s also the onDowngrade).
When this function if called, oldVersion < newVersion.

There is no right or wrong way to manage this function, if you have a static database and need to upgrade it, just delete the old one and create the new one instead.
If you want to add to an existing database with out deleting it just post your SQL Statement there and hope you know what your doing.

Variables:
db – the database.
oldVersion – the old version of the database.
newVersion – the new version of the database.

The basics is right here, in fact you don’t need any more to effectively manage a small database.

Thanks for reading, i am working on the next chapter in the SQLite database tutorial.

Advertisements
Categories: Android, Java Tags: , , , ,

Creating a successful Enum with Java

Enum is basically a dictionary to work with, that gives the programmer a better representation of data through out the application, while maintaining the consistency of the data through different modules.

So what is a successful Enum… the best way to explain is to give a little demonstration on how to upgrade your basic Enum to something more useful.
Application <—> Database is a powerful and common situation to work with.

First of all, an Enum is a class like any other, thus having contructors, members and functions like any other class, and we can use them to our advantage.

Lets begin with a simple week days Enum

enum weekDays
{
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
}

The first problem with this Enum is that its inconsistent with the week days (ha ha why?), because Sunday is not day 0, but day 1. (with out the philosophical debate, Sunday is the First day of the week, and if you want it to be Monday thats OK too, same rule still applies).
So we want to change the Enum elements values?. In order to do that we need to have a constructor, because when the class loader first loads the Enum it creates an instance for each of the Enums elements, in the code example above the default constructor is called for each of the element and consecutive numbers are given to each element starting with 0.
If we want different values than we will create another constructor.

Now, our Enum should look like this:

enum weekDays
{
Sunday(1) , Monday(2), Tuesday(3), Wednesday(4), Thursday(5), Friday(6), Saturday(7);
private weekDays (int value) { }
}

OK!, this looks more like it… but that too doesn’t help us so much. We have ourselves a small dictionary of the weekdays and we set they’r values to what ever we want them to be but the only problem is that we don’t really have any way of getting that value. if we talked about a calendar database and we have a new calendar entry with weekDays member, we need to have some way of getting that value that corresponds to that Enum element (we might want to insert a new record to the database).
Here is where we make this Enum allot more helpful… if we take into consideration the fact that the class loader instantiates each of the Enum values when the class is read for the first time, we can do the following, and expect to have 7 different immutable’s in the JVM immutable pull, each with a different value according to the values we gave the Enum elements.

enum weekDays
{
Sunday(1) , Monday(2), Tuesday(3), Wednesday(4), Thursday(5), Friday(6), Saturday(7);
private int value;
private weekDays (int value)
{
this.value = value;
}
public int toInt()
{
return this.value;
}
}

So now we can translate from the Enum element to its numeric representation (if you were following this far you probably understand that it could be any representation you want it to be).
if we wanted to insert a new record into the database, getting the numerical representation would be as simple as someWeekDay.toInt();

but what about the other way around… what if we wanted to create an application entities from the data stored in the database… well no problem there.

enum weekDays
{
Sunday(1) , Monday(2), Tuesday(3), Wednesday(4), Thursday(5), Friday(6), Saturday(7);
private int value;

private weekDays (int value)
{
this.value = value;
}

public int toInt()
{
return this.value;
}
public static weekDays fromInt(int value)
{
weekDays retVal = null;
switch (value)
{
case 1: retVal = weekDays.Sunday; break;
case 2: retVal = weekDays.Monday; break;
case 3: retVal = weekDays.Tuesday; break;
case 4: retVal = weekDays.Wednesday; break;
case 5: retVal = weekDays.Thursday; break;
case 6: retVal = weekDays.Friday; break;
case 7: retVal = weekDays.Saturday; break;
}
return retVal;
}
}

By now i think you got the point of making Enums work for you. the point is making the code more understandable and consistent traversing databases application network or any other module or medium that you desire.

if you found this helpful in any way or have something to say about what you have just read. please leave a comment.
Happy coding.

Categories: Java Tags: , , ,
%d bloggers like this: