Categories
PHP Uncategorized

Design Patterns – Singletons in PHP 5.x

Design Patterns (and anti-patterns) are techniques of programming. There are a lot of design patterns. It is upto the programmer to pick and choose which patterns to use based on their needs. Singleton is also a design pattern. A singleton is a type of class which can have only 1 object of its kind through the lifecycle of an application. It is very suitable for database, caching, etc. I will use a database class as an example as it is probably the most-widely used class in web development.

Why use a singleton you ask? A popular practice among PHP4’s developers is to make a database object global then use that variable anything a query needs to be run. It works in small applications and even in not-so-big applications. In enterprise applications where you use hundreds (if not thousands) of variables, there is a very good chance that you database object will get mutated or overridden. You also don’t want to have multiple instance of a database class (unless you are running a multi-threaded application).

A database class should be able to connect to a database, run queries, return results and close the connection to the database when it’s done. Keeping that in mind, let’s start writing our database class.

/**
 * Database wrapper
 */
class Database {
	private $_host;
	private $_user;
	private $_pass;
	private $_name;
	private $_conn;
	private $_err;

	/**
	 * Setting the constructor as private will make sure
	 * that the class cannot be instantiated using the
	 * "new" keyword. You can to instantiate it like this :
	 * $db = Database::getInstance();
	 * getInstance() is implemented right after the constructor
	 */
	private function __construct($host, $user, $pass, $name)
	{
		$this->_host = $host;
		$this->_user = $user;
		$this->_pass = $pass;
		$this->_name = $name;
	}

	/**
	 * This function is what makes this whole class a singleton.
	 * It will make sure only one instance of this class is available
	 */
	function getInstance($host='', $user='', $pass='', $name='')
	{
		static $obj;
		if (null == $obj) {
			$obj = new Database($host, $user, $pass, $name);
			$obj->connect();
		}
		return obj;
	}
	/**
	 * Connects to the database
	 */
	function connect()
	{
		$this->_err = null;
		if (!mysql_connect($this->_host, $this->_user, $this->_pass)) {
			$this->_err = mysql_error();
			return false;
		}
		if (!mysql_select_db($this->_name)) {
			$this->_err = mysql_error();
			return false;
		}
		return true;
	}

	function error()
	{
		return $this->_err;
	}

	function user($val=null)
	{
		if (null == $val) return $this->_user;
		$this->_user = $val;
	}
	function host($val=null)
	{
		if (null == $val) return $this->_host;
		$this->_host = $val;
	}
	function pass($val=null)
	{
		if (null == $val) return $this->_pass;
		$this->_pass = $val;
	}
	function name($val=null)
	{
		if (null == $val) return $this->_name;
		$this->_name = $val;
	}
}

So, we wrote a class called database and made its constructor private so you can’t instantiate it using the “new” keyword. We also wrote a method/function for this class called getInstance() which will return a database object. getInstance() has a local static variable called $obj. It checks if this variable is null. If it’s null then that means there is no object of the type “Database”. So, it creates an object and assigns it to $obj. It also returns the object to the code that called it. Setting permissions of private, protected and public could not have been done in PHP 4, which frustrated a lot of OOP enthusiasts. PHP 5, however, has the capability of doing it and thus fulfilling one of OOP’s main goals – encapsulation.

The first time  an object of the class Database is instantiated, it will have to pass all the variables required to make a database connection. Its subsequent calls need not do that.

// First call
$db = Database::getInstance('localhost', 'root', '', 'myDB');

function hello()
{
	// Second call
	$database = Database::getInstance();
}

Both $db and $database point to the same object. Any changes made to $database will be reflected in $db also. This eliminates the use of global variables for quite a few things (especially our database class).

Categories
Android Uncategorized

Working with a database in Android

Android uses SQLite for its database needs. SQLite is a very fast and lightweight database. It is file based which makes it highly portable and an ideal candidate for use as an embedded database. For those who prefer to just go through the code and learn, the Notebook application example on Android’s website can be very useful. Let’s begin with the tutorial shall we.

First, you will need to make a class that will interact with the database. After that class has been written, you will instantiate it and use it to perform your data operations. This will keep your code encapsulated and easy to maintain. Android tries to encourage its programmers to use the MVC concept and makes it easy to implement it.

Assume your table structure is this :

create tblData (
_id int primary key autoincrement,
alert_text text,

alert_date varchar(20),
alert_time varhcar(20)
);

Setting up Connections and getting everything ready

Our database interaction class will be called DBLayer. It is a public class, so it will need to be in a file called DBLayer.java. Let’s say we have a table with 3 fields and we want to set and get data from it. This is how you set the class up :

/**
 * Database Wrapper
 *
 * DB Schema:
 * ------------------------------------
 * Create table tblData (
 *     _id int primary key autoincrement,
 *     alert_text text,
 *     alert_date varchar(20),
 *     alert_time varchar(20)
 * );
 */
public class DBLayer {

	/*******************************************************
	* These constants refer to the fields in the database.
	* _id is Android's naming convention for ID fields.
	* Our database has 3 fields, so we have 3 constants.
	********************************************************/

	public static final String KEY_NAME  = "name";
	public static final String KEY_VAL   = "value";
	public static final String KEY_ROWID = "_id";

	/*******************************************************
	* This is not needed for the database. It is
	* here to help us tag our logging messages
	*******************************************************/
	public static final String TAG = "AlertDB";

	private DatabaseHelper dbHelper ;
	private SQLiteDatabase db;

	private Context mCtx = null;

	/*******************************************************
	* Some other constants related to our database's
	* information. They should be self explanatory
	********************************************************/
	private static final String DATABASE_NAME = "gAlert_db";
	private static final String DATABASE_TABLE = "tblData";
	private static final int DATABASE_VERSION = 2;
	private static final String DATABASE_CREATE =
	"create table gAlert_alerts ( "
	+ "_id integer primary key autoincrement, "
	+ "alert_text text not null,"
	+ "alert_date varchar(20) not null,"
	+ "alert_time varchar(20) not null"
	+");";

	/********************************************************
	* Think of this as a driver for your database
	* interaction. You can just copy and paste this part in
	* all your database interaction classes.
	*********************************************************/
	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context ctx) {
			super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
		}
		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP IF TABLE EXISTS "+DATABASE_TABLE);
			onCreate(db);
		}
	}

	/** Constructor */
	public DBLayer(Context ctx) {
		mCtx = ctx;
	}
	/********************************************************
	* This opens a connection to the database but if
	* something goes wrong, it will throw an exception.
	********************************************************/
	public DBLayer open () throws SQLException {
		dbHelper = new DatabaseHelper(mCtx);
		db = dbHelper.getWritableDatabase();
		return this;
	}
	/** Closes a database connection */
	public void close() {
		dbHelper.close();
	}
}

I have read articles which state a different way using databases in Android. From what I can tell these tutorials were for versions prior to 1.0. In version 1.0, you create a class which extends SQLiteOpenHelper and you encase that class in another class which you will call to insert and retrieve data. The comments in the code above should be self-explanatory. If you have any questions I haven’t answered, please leave a comment and I will post a reply.

You don’t need to have a database already set up. If the database you try to open doesn’t exist, then Android will create it. It will run the onCreate() method when it creates the database. And, if the database version changes on the phone. It will run the onUpgrade() method.

Running your Queries

Now the class DBLayer can connect to the database. However, just connecting is of no use unless you can retrieve some data from your database. There are 4 methods you can use in Android and they all perform different functions. They are : query, insert, delete and update. query() is used to retrieve data. The others should be self-explanatory.

Here’s a method that will retrieve multiple rows from the database:

	public Cursor fetchAllAlerts() {
		try {
			return db.query(DATABASE_TABLE,
				new String[] {KEY_ALERT_TEXT, KEY_ALERT_DATE,
				KEY_ALERT_TIME, KEY_ROWID}, null, null,
				null, null, null);
		} catch (Exception e) {
			Log.e("yo", e.getMessage());
			return null;
		}
	}

You will rarely (if ever) find yourself writing any SQL for Android applications. The reason being Android’s framework does all the dirty work behind the scenes. All you have to do is set  your object up and provide the data retrieval, insertion methods with the neccesary information.

Here are some more methods. Everything should be self explanatory.

	public long createAlert(String text, String date, String time) {
	ContentValues vals = new ContentValues();
	vals.put(KEY_ALERT_TEXT, text);
	vals.put(KEY_ALERT_DATE, date);
	vals.put(KEY_ALERT_TIME, time);
	return db.insert(DATABASE_TABLE, null, vals);
}

public boolean deleteAlert(long rowId) {
	return db.delete(DATABASE_TABLE, KEY_ROWID+"="+rowId, null) > 0;
}

public Cursor fetchAllAlerts() {
	try {
		return db.query(DATABASE_TABLE, new String[] {
				KEY_ALERT_TEXT, KEY_ALERT_DATE,
				KEY_ALERT_TIME, KEY_ROWID}, 
					null, null, null, null, null);
	} catch (Exception e) {
		Log.e("yo", e.getMessage());
		return null;
	}
}

public Cursor fetchAlert(long rowId) throws SQLException {
	Cursor ret = db.query(DATABASE_TABLE, new String[] {
				KEY_ALERT_TEXT, KEY_ALERT_DATE,
				KEY_ALERT_TIME, KEY_ROWID},
				KEY_ROWID+"="+rowId, null, null,
				null, null);
	if (ret != null) {
		ret.moveToFirst();
	}
	return ret;
}

public boolean updateAlert(long rowId, String text, String date, String time) {
	ContentValues vals = new ContentValues();
	vals.put(KEY_ALERT_TEXT, text);
	vals.put(KEY_ALERT_DATE, date);
	vals.put(KEY_ALERT_TIME, time);
	return db.update(DATABASE_TABLE, vals,KEY_ROWID+"="+rowId, null) > 0;
}

You can get the code for the whole class here. In this article, there wasn’t much explanation because I didn’t think I needed to explain anymore after pasting the code. I am sure there are people reading this who feel otherwise. Please let me know what needs more explanation and I will elaborate on that topic.

Categories
Uncategorized

Installing Blackberry’s JDE

Blackberry provides an SDK for developers who want to develop applications for a Blackberry device. And, like all other mobile SDKs I have come across the documentation doesn’t answer all your questions. So, here is a short tutorial to satisfy the hunger for programming Blackberry devices.

You will need Blackberry’s JDE. You can download it from here :

http://na.blackberry.com/eng/developers/javaappdev/javadevenv.jsp

Don’t download the eclipse plugin. It is for programming MIDlets which deal with J2ME. You will also need to download and install JDK from sun.com. Just getting the JRE is not enough, you need the whole JDK.  You can get JDK from here :

http://java.sun.com/javase/downloads/?intcmp=1281

Java 6 update 10 is the latest version of JDK and 4.6 is the latest version of Blackberry JDE at the time of this writing.

Install JDK first. After installing the JDK click on Control Panel -> System . Click on Advanced tab and then click on “Environment variables”. A dialog will popup. Select the PATH variable and click Edit. Assuming you installed JDK in the default path, add the line below in the text box that says “Variable value” :

;c:\program files\java\C:\Program Files\Java\jdk1.6.0_10\bin

If you installed the JDK somewhere else or installed a different version, then change the path accordingly. Make sure there is a semi-colon (;)at the beginning of the path you insert.

Now that the JDK installed, install Blackberry JDE (double click on the installation file). It will find the default JDK’s path from the location you entered in the environment variable “PATH”. After JDE is done installing, you should be able to run it without any problems. Click Start -> Research in motion -> JDE to run it.

Click to enlarge
Click to enlarge
Click to enlarge
Click to enlarge
Click to enlarge
Click to enlarge
http://s95.photobucket.com/albums/l132/marc188/blog/blog4.png
Click to enlarge
Categories
Android Uncategorized

Debugging errors in Android

Android has a great framework to work in. However, it is in its infancy and debugging my code has been a very big problem for me. Whenever something goes wrong in the code, I always get “source not found” error. It doesn’t tell me I have a nullPointer exception , or string is incomplete.  No matter what’s wrong with the code, I always get “source not found” error. The reason that happens is Android doesn’t pack the source along with the application it sends to the emulator (maybe they should do that for a debugging run). After searching the net for a while, I came across this solution – wrap your code in a try and catch block and then log the exception to console. Here is an example :

public class SomeClass extends ListActivity {
	private AlertDB db ;
	private static final int ALERT_ADD = 100;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	//setContentView(R.layout.alert_list);
	try {
		db = new AlertDB(this);
		Cursor c = db.fetchAllAlerts();
	} catch (Exception e) {
		Log.e("ERROR", "ERROR IN CODE:"+e.toString());
	}
}

Doing that will display a neat little line in your logcat window (look at the screenshots at the bottom). And, instead of getting the annoying “source not found” error. You will know what the actual error is. In Android, you can log three types of events – information, warning and error. Information is just verbose text being written out to the log.  I don’t need to explain warning and errors.

For logging information you can use :

Log.i(TAG, message);

For logging warnings you can use :

Log.w(TAG, message);

I have already shown how to log errors in the code above.

Click to enlarge
Click to enlarge
Click to enlarge
Click to enlarge
Categories
Android Uncategorized

Programming for the beast named Android

Click for original size
Click for original size

I was messing around with Android’s development kit and I have to say, learning to develop an application for Android was much easier than trying to do it for Windows Mobile. I guess proper documentation helps – a lot. Google has put published tutorials on how to do some common tasks needed for making applications, and has  code reference documentation, etcetera which makes it easier to jump into it.

I am a very big fan of MVC and code and design separation in general. I was happy to find out that Android’s API lets you design the user interface in XML and then use that in your program. You can also do the design programmatically but who wants to do that (unless maybe you were adding / removing elements dynamically).

Google also provided an emulator to debug your software. It would have been a nightmare debugging my application without it. Beware of the “source not found” error. Whenever something goes wrong in your application, the debugger tries to reference the source of the place of error. And, the compiler doesn’t include source in the binary from what I understand. So, you get the debugger throws the error “Can’t find source”. There are workarounds for that problem posted on the internet, though.

When I started learning how to program for Windows Mobile (I have a Kaiser so I wanted to an FTP editor for it to edit HTML/PHP/whatever on the go). It took me quite some time to realize that you HAVE to buy Visual Studio if you want to program for it. It took me about a week to get started with Windows Mobile development but it took me a day for Android. And, the studio costs hundreds of dollars so that was out of the question for a hobby. Android, on the other hand, is free so I can use it with no cost at all. Don’t get me wrong. I am not putting Microsoft down. I am a programmer too and I know better than to say all software should be free. People need to make money and without an incentive there won’t be any good software. Visual Studio has great features which make programming very easy. I love their UI designer. I just want to have the choice to be able to program with their SDK without having to shell out 500+ dollars. Maybe if they let me use the SDK for free and asked to be paid for the visual studio, it would be a beter deal.

Anyway, after I got interested in the Android’s SDK, I decided to write some useful applications for it. I’m sure there will be enough users of Tmobile’s G1 phone who will want to use my application *fingers crossed*. Maybe I will make another post of what I plan to make that application do (hint: it will use geo-location service, run in the background and have a UI for settings and such).

Links:

Android’s home page :
http://www.android.com/

Resources for developers :
http://code.google.com/android/

Tutorials on various android related things :
http://developerlife.com/tutorials/?p=304

Categories
Uncategorized

Programming for Windows Mobile

If you are too used to programming in Linux and want to move to programming for Windows mobile. It can be a bit hard. It was difficult for someone I know to digest that the SDK requires that you have Visual Studio installed (the full version not the express edition).  So, here are a few directions for those who wish to venture into windows mobile programming.

You will need to install .Net Compact Framework 2.0 and 3.5. You can install just 3.5 but it’s better to have both.  You will need to install Visual Studio. The latest version of Visual Studio is 2008. WHen you have both of them installed, you can install the WIndows mobile 6 SDk refresh and Windows mobile 5 SDK refresh. And viola ! you can now start programming for windows mobile devices. From what I understand, you can’t program for Windows Mobile outside of Visual Studio. Well there is nothing stopping you from just opening notepad and coding but you have to have Visual Studio installed (along with the other things I mentioned).

As you might already know, there are 2 modes of programming in .NET – managed and unmanaged. Any programs written in C# or Visual Basic are managed; and, anything written in C++ is unmanaged. What does that mean? It means memory is managed for you behind the scenes in C# and Visual Basic. However, you have to do your own memory management (free up memory space,  etc). Each of them have their own pros and cons.

Now open Visual Studio and click on new project. Select Smart Device -> Smart Device Project. A new project will be created for you with a default form in design view. On the left you will find a toolbox, which has widgets (controls) for your UI. On the right, you will see a properties section where you can set properties, event handlers, etc for your controls. This should at least help you get started with the setup part of it.

Categories
Exploring NYC Uncategorized

National Museum of American Indian

Most of the people who live in New York City take it for granted (including me). So, I decided to explore this beautiful city and see what it has to offer in terms of heritage, activities, etc. I was not dissapointed. I went to the National Museum of American Indian and they had all sorts of things related to Red-Indian culture.

I liked the architecture of the museum. It had beautiful art on the ceiling in the main hall. There were numerous charts, pictures and articles explaining how they (Red Indians) make leather and stitch clothes from them. The decorations that are used (and the materials they made the decorations from), etc. Many dresses were also on the display (one of which was over 500 years old).

Admission to the museum is free. It is open from 10:00 AM – 5:00 PM. However, it is always a good idea to call ahead. Their contact information is :

One Bowling Green
New York, NY 10004
Phone: 212-514-3700
Website: http://www.nmai.si.edu/

Here are some pictures from my visit. I apologize for the small size of the pictures. My phone was set to contact pictures instead of regular ones and I was too excited to notice. Maybe I will go there again and get some more pictures.

Categories
Uncategorized

My own blog

Hello Everyone,

Welcome to my blog.