Share your knowledge and create a knowledgebase.

Archive for the ‘PHP’ Category



There are literally over a hundred of JavaScript frameworks out there that make writing complex client-side code significantly easier. If you’re in the market for a powerful, relatively lightweight, and customizable JavaScript framework, MooTools is worth checking out.

To help you get on your way to developing highly-interactive web applications using MooTools, here’s 20 tutorials and working examples that’s worth a read.

Getting Started with MooTools

1. The “Mootorial”

The Mootorial - Screenshot

The Mootorial at //clientside is a comprehensive, practical tutorial on the MooTools framework. The tutorial allows you to execute the sample code either by Firebug or the website’s built-in console.

2. MooTools Overview Video Tutorial

Here’s an excellent screencast that introduces the MooTools framework. It covers the basics such as the concept of chaining, customizing MooTools to your needs, and where to find documentation for MooTools code.

3. Increasing User Experience With Javascript

Increasing User Experience With Javascript - Screenshot

Beauty By Design provides a nine-part video series on improving user interaction using JavaScript (primarily MooTools). A couple of topics covered in the lessons include: using mooTabs, creating sliding sub menus, and using Fx.styles to control font size.

4. Understanding Mootools Selectors

One of the most powerful features of MooTools (as well as other frameworks/libraries like jQuery and Prototype) is the ability to easily select page objects for you to work on. This tutorial covers the basics of selectors in MooTools: $(), $$(), $E(), and $ES() functions.

5. MooTools MooTools Classes: How to use them

This tutorial is an entry-level introduction on working with classes in MooTools. The tutorial works with a hypothetical scenario (buying a car from a car store) to illustrate the concept of classes. The last section of the article discusses the differences of MooTools and script.aculo.us classes.

Intermediate/Advanced Topics

6. Mootools: Ajax and XHR classes

MooTools’ Ajax/XHR classes provides developers a much simpler way of working with XMLHTTPRequests by reducing the amount of code you have to write and by handling browser differences for you. This tutorial talks about the Ajax and XHR classes in brief.

7. Ajax Responder in MooTools

This article delves into the use, extension, and capabilities of the Ajax class in MooTools. It discusses chaining Ajax requests and events, and how you can extend the Ajax class for your needs (also applicable to other MooTools classes).

8. How well do you know Mootools?

Getting started with MooTools is easy, and it won’t be long until you can create wonderful effects and increase user interactivity in your web pages. To help you become a MooTools master, here’s a checklist of common coding mistakes and its corresponding correct usage.

9. Mootools Short-cuts

This is a follow-up article from the one above, focusing more on MooTools syntax usage. Examples involve using shorter code for selection of objects, shorthand for the Ajax class, and creating new elements.

10. Mootools: JSON explained

Mootools: JSON explained - Screenshot

Here’s an excellent introduction to using JSON with MooTools to provide server-side interaction to your web applications. Topics covered include converting a JSON string into a JavaScript object and vice versa.

11. Using MooTools’ Hash.Cookie API

This article explains how to take advantage of MooTools’ powerful Hash.Cookie API to make working with complex cookie utilization a cinch. The example showcases a working example of how you can store the number of times a user visits a page.

12. Chaining with MooTools 1.2

Chaining is beneficial for several reasons including the ability to sequentially execute events (”in a chain”) as well as reduce the number of lines of code you have to write. If you’re wondering about the “who, what, where” of chaining in MooTools, check out this brief but informative tutorial.

Practical/Working Tutorials and Examples

13. AJAX mootools secure contact form

AJAX mootools secure contact form - Screenshot

Learn how to protect your public web forms from spam and SQL injections with this tutorial on how MooTools can be used to make safer public web forms.

14. Using CSS and Mootools to simulate Flash horizontal navigation effect

Using CSS and Mootools to simulate Flash horizontal navigation effect - Screenshot

Create a navigation area that smoothly scrolls left or right depending on where you hover your mouse.

15. Facebook Sliders With Mootools and CSS

Facebook Sliders With Mootools and CSS - Screenshot

Check out this nifty tutorial on how to build a Facebook-inspired set of slider controls that manipulate the opacity, width, and height of an image.

16. MooTools Gone Wild: Element Flashing

MooTools Gone Wild: Element Flashing - Screenshot

In this tutorial, you’ll learn how to make page elements flash. It’s an effective way of drawing attention to a particular section of a web page or alerting users of status changes.

17. Nice Ajax effect for message box using Mootools

Here’s a tutorial on how to display messages that fades in after the user clicks on the submit button. It’s designed for use with web forms, but it can be modified into similar applications.

18. Two CSS vertical menu with show/hide effects

Two CSS vertical menu with show/hide effects - Screenshot

This tutorial shows you how to build a navigation menu that slides up and down smoothly using MooTools. The article also covers how to make a similar effect using plain JavaScript.

19. Mootools Content Slider With Intervals

Mootools Content Slider With Intervals - Screenshot

Here’s an excellent step-by-step tutorial on how to make a content area that slides left-to-right at set intervals – great for slideshows.

20. Jazz Up Your Forms With MooTools

Jazz Up Your Forms With MooTools - Screenshot

This is a two-part series that goes over how to make your web forms fancier. The first part shows you how to add animated field highlighting and how to display instructions to users. In the second part, you’ll step it up a notch by adding live comment previewing and auto-resizing of text areas.

Additional Tools

  • Vista like JavaScript/PHP DatePicker : The Vista-like Ajax Calendar (vlaCalendar) version 2 is a unobtrusive  web version of the slick and profound Windows Vista taskbar calendar, by using the MooTools javascript framework, AJAX, XHTML, CSS and PHP.vlaCalendarExamples.jpg
    Key features:
  • Authentic Vista look-and-feel
    • Quick navigation by jumping back and forth between months, years and decades without drop-down boxes
    • Smooth transition animations
  • Customizable features
  • Lightweight
  • Datepicker functionality (!)
  • Cleaner and more developer centered - easily editable - CSS, PHP and javascript code
    • Easily changeable date labels (e.g. different languages)
    • Easily stylable. Styles are created on top of the general style; the download include two example styles
    • Both normal and datepicker calendar can be instantiated multiple times

Please post your experiences with the above tools. If you like this post kindly subscribe to our RSS for free updates and articles delivered to you.


Aug 5, 2008 Author: Ashish | Filed under: AJAX (Asynchronous JavaScript and XML), JavaScript, PHP

iphoneshot Copy and Paste Finally Coming to the iPhone

Copy and Paste has long been one of the most requested features on the iPhone, and its continued absence has been both frustrating and confusing for many. How can it be that the iPhone - running a finely tuned version of Mac OS X - is unable to perform functions that have been included in text editors since the 80’s?

MagicPad, a new application from Proximi that is currently waiting for approval on Apple’s App Store, is finally making copy and paste a reality on the iPhone. The application is essentially an improved version of “Notes”, and features rich text editing, allowing users to modify font type, size, and color. And best of all, it allows for copy and paste. Users need only drag their fingers over text to select it, and adjustments can then be made on a menubar that appears above the onscreen keyboard (see the video below).

Unfortunately, MagicPad isn’t going to bring true Copy-and-Paste to the iPhone, as there will be no way to copy text between applications (say, from Safari to the Mail client). You’ll be able to copy and paste between multiple notes within MagicPad, which will make it a step up from Notes, but in reality it serves as more of a proof of concept than a solution.

So when will we finally get true, systemwide, copy and paste? Earlier this month, Apple’s Greg Joswiak finally commented on the issue, explaining that it was on Apple’s to-do list but that it hasn’t been a priority. The lengthy wait is almost certainly due to issues with creating an intuitive interface for copy and paste on the iPhone’s buttonless touchscreen. MagicPad’s interface looks like it works well enough, but it takes up a large portion of screen real estate and is less elegant than what we’ll probably see from Apple.

Thanks to Apple iPhone Apps for the video.

First Look - MagicPad from Apple iPhone Apps on Vimeo.


Jul 29, 2008 Author: Ashish | Filed under: PHP, iPhone

Nice URLs, readable URLs, search-engine-friendly URLs. Different names same deal.

It can’t really be disagreed on that something like example.com/index.php?page=article&id=409 is not nearly as nice as example.com/article/409.

Turns out this isn’t all that hard with PHP - infact it can turn into something that’s very useful from more than just a readability viewpoint.

The Plan

What we’re going to do is capture everything past a particular point in our URL and pipe it to PHP, we’re going to let PHP do most of the the legwork.

* Using mod_rewrite we get everything past a particular point.
* We will then pass that into a PHP get variable. We’ll use “p”, you can use anything.
* In our PHP we will define “rules” for our URLs with very simple regular expressions.
* When something matches, we’ll get the appropriate page - otherwise we’ll give back a 404.

mod_rewrite

Yep, this article is purely from an Apache perspective, so I assume that you not only have Apache on your webserver, that you also have enabled mod_rewrite.

If you haven’t enabled mod_rewirite, it’s usually something like this in your http.conf:

LoadModule rewrite_module modules/mod_rewrite.so

Remember to restart Apache afterwards.

.htaccess

Let’s get .htaccess out of the way now. These are special files that you may, or may not have come accross. Basically, Apache will read these set of definable rules and determines what to serve when you visit a page.

In this case we’re going to use mod_rewrite rules. So, first create a file called .htaccess and open it up. (To Windows folk - It really has no “filename”, this might confuse some of the poorer text editors.)

To start with, we’re going to check if mod_rewrite is enabled - if it isn’t then Apache will return an internal server error (500).

All our rules will go inside this block.

First we need to enable the rewrite engine and set our base.

RewriteEngine on
RewriteBase /

The RewriteBase will tell Apache exactly where our capturing needs to come from, what the relative path is.

In our case we’re assuming we’re rewriting the root of a URL. If your script resided in a sub-directory like http://example.com/test, RewriteBase would have to be written like so:

RewriteBase /test

Our first rule will tell Apache where to go when we haven’t specified anything, in this case we simply want to go to index.php:

RewriteEngine on
RewriteBase /
 
# Nothing - Go to index.php
RewriteRule ^$          index.php  [L]

RewriteRule is how we define our actual rules.

Rewrite rules use regular expressions (regex for short), a kind of special text processing language, to define the rules. They can become very useful if you learn them properly, and we shall be using them later when we write the PHP portion of this article. PHP comes with reasonably good regex support built in.

In this case our regular expression is ^$. The caret symbol, ^, means “At the start”. The dollar sign, $, means “At the end.” So this pattern effectively matches nothing, there is nothing between the two symbols.

Don’t worry if regular expressions are confusing at first, there are many tutorials on it around.

The second part of RewriteRule defines where our rule goes to, in this case we always want an empty path to go to index.php.

The last part in square brackets defines a special flag, here we use the L flag. L defines this rule as the “last one” - if this rule matches then Apache will disregard any further ones.

Our next rule is the one that we came here for:

RewriteEngine on
RewriteBase /
 
# Nothing - Go to index.php
RewriteRule ^$          index.php       [L]
 
# If anything matches, send the path to index.php
RewriteRule (.*)        index.php?p=$1  [L]

In regex a fullstop means “any single character” and asterisk means “one or more of the previous character”. So our pattern is effectively - any amount of any character or simply, everything.

The parentheses around the rule indicate we want to group that match, and use it later. We do use in defining where our pattern goes to. You refer to groups with the dollar sign and the number of group. (Groups start at 1.) Again we will define this as the last rule with [L].

So with these two rules http://example.com will invisibly redirect to index.php and http://example.com/page/409 will rewrite to index.php?p=page/409.

Unfortunatly, if you try to go directly to any other file or directory, it will not show up - Instead the path will get sent to index.php! We can use RewriteCond to add additional conditions to rectify this situation.

RewriteEngine on
RewriteBase /
 
# Nothing - Go to index.php
RewriteRule ^$          index.php        [L]
 
# Condition - requested path is not a file or directory.
RewriteCond %{REQUEST_FILENAME}         !-f
RewriteCond %{REQUEST_FILENAME}         !-d
 
# If anything matches, send the path to index.php
RewriteRule (.*)        index.php?p=$1  [L]

In a little bit of slightly backward behaviour, when Apache finds a rewrite rule it will go back to see if there were any conditions and check those before finally matching. So these conditions must appear before the rule.

The first parameter is what we test against, it refers to a special server variable, in this case REQUEST_FILENAME. The second parameter is our actual condition. -f asks “Is an existing file” and -d is directories.

Since we only want to continue if the match is not a file we can use a !, so our final patterns are !-f and !-d.

Our rewrite ruleset is nearly complete, but there’s one tiny thing, sometimes you may want to pass GET parameters around in the URL the same way you normally would, as it stands these will be ignored by Apache when rewriting. We can use a flag to append all extra request parameters to the URL - QSA.

Our final .htaccess file looks like this:

RewriteEngine on
RewriteBase /
 
# Nothing - Go to index.php
RewriteRule ^$          index.php       [L]
 
# Condition - requested path is not a file or directory.
RewriteCond %{REQUEST_FILENAME}         !-f
RewriteCond %{REQUEST_FILENAME}         !-d
 
# If anything matches, send the path to index.php
RewriteRule (.*)        index.php?p=$1  [QSA,L]

If anything about mod_rewrite is confusing it’s worth knowing that the documentation on it is actually not all that terrifying and can help you understand it much better.

Using PHP to get the requested URL

Our rewrite rule will pipe everything into index.php as a GET parameter called “p”. So everything in our script will need to be included through this.

To start our index.php file we need to define a list of matches.

/*
 * Work out what page we are on
 */
$page_rules = array(
  "index" => "home.php",
  "about" => "about.php"
);
 
$page_val = (isset($_GET['p'])) ? $_GET['p'] : "index";

$page_rules is an associative array pointing matched rules to special pages. You can keep your eventually pages whereever you like, for our example we’ll simply have a “pages/” subdirectory where these will go in.

We set $page_val to our “p” parameter if it was set, otherwise defaulting to index.

Next we go through all our rules and find if we’ve matched one with our parameter.

/*
 * Work out what page we are on
 */
$page_rules = array(
  "index" => "home.php",
  "about" => "about.php"
);
 
$page_val = (isset($_GET['p'])) ? $_GET['p'] : "index";
 
/*
 * Iterate through rules and test them on our request
 */
$match = NULL;
 
foreach($pages as $regex => $page_to)
{
 
  if(preg_match("/^".$regex."$/i", $page_val))
  {
    $match = $page_to;
    break;
  }
 
}
 
/*
 * If we didn't match anything deliver a 404 or include our file
 */
if($match === NULL)
  die("404");
else
  require "pages/".$page_to;

We now use preg_match to match against each of our rules.

For our index rule, the regular expression looks like /^index$/i. The forward slashes indicate the start and end delimeters of the regex, we can use extra flags to define special things, in this case we use the i flag which indicates that the match is case insensitive.

When we match a rule, we save the page name, then serve it later, or give a 404 message if not. (Your 404 message should be a lot better - this is a simple example after all.)

At this point our rewriting will work perfectly fine. There’s a few issues to work out first.
Small issues

First off, if you go to http://example.com/about the rule works, but if you go to http://example.com/about/ then nothing matches - our p variable has changed with that one character!
Luckily we can expand our regular expression to account for this. Question mark, ?, means “the previous character none or more times”. So /? would mean “forward slash or no forward slash”, except that as we know, forward slash means something in regular expressions. To escape characters in regex simply use the backslash character. The correct match is \/?.
Our new rule check looks like this:

if(preg_match("/^".$regex."\/?$/i", $page_val))
{
$match = $page_to;
break;
}

You may be starting to think that regular expressions can start to look messy the more complicated they get - you’d be right, but that doesn’t discount how useful they can be. A regular expression can be broken down into smaller parts if necessary.
This leads on to our second problem, if any of our matches have a forward slash in, which they most likely will, you will get an error when hitting the regex because it would be unescaped. A quick str_replace will sort that.

$regex = str_replace("/", "\/", $regex);
 
if(preg_match("/^".$regex."\/?$/i", $page_val))
{
$match = $page_to;
break;
}

Grouping
This is all well and good, but if you have a URL like our initial example of http://example.com/article/409 surely you’d have to make a new rule for each ID? Luckily we can leverage the power of regex to do that for us.
First we need to ammend our rules to match /article/ and any number. This is done like so:

$page_rules = array(
  "index"          => "home.php",
  "about"          => "about.php"
  "article/[0-9]+" => "article.php"
);

[0-9] is a range, a single number from 0 to 9. And whereas ? means “zero or more times”, in this case we need to use plus, + which means “one or more times“. So we’re now matching any integer.
Great, our rule works! But it’s useless to us if we can’t get that parameter out. Well, first we need to define this as a group in our regex by using parentheses, the same way we did in our .htaccess rules before.

$page_rules = array(
  "index"            => "home.php",
  "about"            => "about.php"
  "article/([0-9]+)" => "article.php"
);

To get our groups out of our regular expression we need to use the third parameter of preg_match, in which we pass in an array that will then be filled with our groups.
Our foreach loop needs to look something like this:

$match = NULL;
$matches = array();
 
foreach($pages as $regex => $page_to)
{
 
$regex = str_replace("/", "\/", $regex);
 
if(preg_match("/^".$regex."\/?$/i", $page_val, $matches))
{
$match = $page_to;
break;
}
 
}

Great, now if you tried to go to /article/409 and did a print_r of $matches, you’d get something like:
Array

(

[0] => article/43/

[1] => 43

)
The first entry is filled with the entire pattern, the second one is our requested ID - the group we defined in our match.
Notice that because we’ve defined any number, if you try to enter anything other than a number into the URL as an ID you will get given a 404 - This can act as a kind of first-defense validation for input variables.
This is almost the end of the article, however we can make this a little nicer to work with.
Named groups
Being able to refer to something like $_GET[’id’] is a convenience, there’s a name. $matches[1] is not so easy to dechyper - or even keep track of, what if we add another group that appears before it like a category name - the group number may shift.
Luckily with regex we can name our groups using the simple syntax of ? inside the start of the group. Our new rules can now look like this.

$page_rules = array(
  "index"                 => "home.php",
  "about"                 => "about.php"
  "article/(?<id>[0-9]+)" => "article.php"
);

Now when you print_r $matches you get:
Array

(

[0] => article/43/

[id] => 43

[1] => 43

)
You can still refer to the group as $matches[1], but we’re also given the option of $matches[’id’].
Conclusion

Our final PHP script looks like this:

/*
* Work out what page we are on
*/
$page_rules = array(
"index"                 =&gt; "home.php",
"about"                 =&gt; "about.php"
"article/(?[0-9]+)" =&gt; "article.php"
);
 
$page_val = (isset($_GET['p'])) ? $_GET['p'] : "index";
 
/*
* Iterate through rules and test them on our request
*/
$match = NULL;
$matches = array();
 
foreach($pages as $regex =&gt; $page_to)
{
 
$regex = str_replace("/", "\/", $regex);
 
if(preg_match("/^".$regex."\/?$/i", $page_val, $matches))
{
$match = $page_to;
break;
}
 
}
 
/*
* If we didn't match anything deliver a 404 or include our file
*/
if($match === NULL)
die("404");
else
require "pages/".$page_to;
 
?&gt;

We’ve implemented friendly URLs in a simple way that is also very easy to work with in your script, we even have some basic validation that wouldn’t get relying on $_GET.


Jun 24, 2008 Author: Ashish | Filed under: PHP

Relational Database Design is one of the most powerful ways to ensure data integrity and a great way to kick-off any project. Very often the first thing developers do when starting a new project, or stub-project, is to design the database. This way the structure of the application is already in place and we just have to fill in the pieces with some server-side code. I’ve found when adding relational constraints to your database design you add in a very powerful error reporting tool that will let you know during the development process that you have allowed something to happen that shouldn’t have. In this article, I go through, step by step, showing how to set up a simple relational database and discuss the benefits that are enjoyed.

Let’s take a step back and describe what a relational database looks like. In any normal database design there are fields in one table that reference another table. For example, a books table might have a field labeled author_id which is meant to come from a table named authors. Creating hard-coded relations solidifies these associations and actually returns a MySQL error if violated.

As I hinted in the opening I have found this to be invaluable during the development and testing process as MySQL will immediately let me know that I have made a glaring error that otherwise may not have been noticed until after the service has launched. At that point the data could be irreparably corrupt and forced to start from scratch.

So let’s get right to it. For the purposes of this article, I’m going to pretend I’m creating a simple Books and Authors website with a simple 2-table setup. The first step is to create our tables.

  1. CREATE TABLE `library`.`books` (
  2. `id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  3. `name` VARCHAR( 150 ) NOT NULL ,
  4. `author_id` INT UNSIGNED NOT NULL ,
  5. PRIMARY KEY ( `id` ) ,
  6. INDEX ( `author_id` )
  7. ) ENGINE = InnoDB

  1. CREATE TABLE `authors` (
  2. `id` int(10) unsigned NOT NULL auto_increment,
  3. `name` varchar(50) collate utf8_bin NOT NULL,
  4. PRIMARY KEY  (`id`)
  5. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin

Relational Database - 1

Nothing too fancy here. Couple things to notice:

  1. Each table MUST be using the InnoDB storage engine. InnoDB is currently the only main-stream storage engine offered by MySQL to support relational design. More on this in my article: MyISAM vs InnoDB
  2. The `author_id` field in the `books` table MUST be indexed and the same datatype as the `id` field in `authors`.

The next step is to set up the relations. Open the `authors` table and take a look at the view. Under the table there should be a link titled ‘Relation View’ - Click it.

Relational Database - 2

phpMyAdmin has a great gui for setting up relations and actions. If the `author_id` row below doesn’t look like mine, make sure you have it indexed.

Relational Database - 3

Here, I’ve setup a link on the `books` table and the `author_id` field. This will enforce the fact that any value inserted in this field MUST be present in the `authors.id` table as well. But what about these other settings?

ON DELETE:

  • CASCADE:
    • This means if an author is deleted from the authors table, all of his books will also be automatically deleted.
    • This option is great to keep your data clean and reduce the number of delete quieries required when deleting an author.
  • SET NULL:
    • Instead of deleting the book record when an author is deleted, books.author_id is set to NULL, effectively orphaning the book.
    • This feature is great if you want to be able to keep the books and come back at a later time to reassign them. Otherwise, without this feature, the books would still be referencing an author_id that doesn’t exist.
    • Note: If you try to set this option and phpMyAdmin tells you to check your datatypes, make sure the field is allowing null values.
  • NO ACTION:
    • When a delete query is issued on an author that has books, MySQL will not allow this and return a Foreign_Key Constraint error.
    • It could be nice to identify this and re-word it to let the user know that if they would like to delete this author they need to re-assign his books or delete them all-together.
    • Note: If you use this option please remember to re-word the MySQL error to something the user can easily understand.
  • RESTRICT:
    • Same as NO ACTION
    • From MySQL Manual: Some database systems have deferred checks, and NO ACTION is a deferred check. In MySQL, foreign key constraints are checked immediately, so NO ACTION and RESTRICT are the same.

ON UPDATE:

  • For the most part the options described above are going to act in the same manner they did for ON DELETE as they will with ON UPDATE. I’ll just run through some examples real quick.
  • CASCADE:
    • If, for some reason, an author’s id gets updated than CASCADE will update all his corresponding books with the new value. Extremely handy.
  • SET NULL
    • Same as CASCADE except instead of updating it with the new value, it will set it to null. I’m sure there is a perfectly good use for this but I haven’t run into it yet. If anyone can enlighten me please do :)
  • NO ACTION / RESTRICT:
    • Same as ON DELETE, will throw an error if you try to update an author_id. I’m also having trouble finding a real-world example of when this could be useful

Once we have our simple relational database configured try to add a book with an author_id that doesn’t exist. MySQL should give you an error like this:

Cannot add or update a child row: a foreign key constraint fails (`library/books`, CONSTRAINT `books_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)


Jun 18, 2008 Author: Ashish | Filed under: MySQL, PHP

On Monday, November 12, 2007, Google released Android, a complete Linux based software stack aimed directly at the cell phone marketplace. I’ll let others talk about what it means for other players in the marketplace, the intricacies of GPL2 vs the Apache License, etc. This article dives straight into the heart of the SDK and API itself, summarizing some of the documentation provided by Google, then jumping into building an application using Android.


Android Emulator

(Click to enlarge)

So, what Is Android?

Android is a complete software stack for mobile devices such as cell phones, PDAs and high end MP3 players. The software stack is split into four layers:

  • The application layer
  • The application framework
  • The libraries and runtime
  • The kernel

Cell phone users obviously work with applications in the application layer. Android developers write those applications using the application framework. Unlike many embedded operating environments, Android applications are all equal — that is, the applications that come with the phone are no different than those that any developer writes. In fact, using the IntentFilter API, any application can handle any event that the user or system can generate. This sounds a bit scary at first, but Android has a well thought-out security model based on Unix file system permissions that assure applications have only those abilities that cell phone owner gave them at install time. The framework is supported by numerous open source libraries such as openssl, sqlite and libc. It is also supported by the Android core libraries — more on that in a second. At the bottom of the stack sits the Linux 2.6 kernel, providing the low level hardware interfaces that we all expect from a kernel. This is a Unix based system — that is, the Unix C APIs are available — but don’t expect to drop to a shell and start executing shell scripts with your old friends grep and awk. Most of the Unix utilities are simply not there. Instead Android supplies a well thought out API for writing applications — in Java using the Android core libraries.

That’s right, Android applications are almost exclusively written in Java. The Android core library is a big .jar file that is supported by the Dalvik Virtual Machine — a fast and efficient JVM work-alike that enables java-coded applications to work on the Android cell phone. This is similar to, but not the same as using Sun’s JVM directly.

Building your development environment

Google provides three versions of the SDK; one for Windows, one for Mac OSX (intel) and one for Linux (x86). They also provide two development environments — one is Eclipse based, and the other is a “roll your own.” The Eclipse based environment is quite feature-rich and should suffice for most developers. There is no reason that you can’t use both Eclipse and “roll your own.”

If you get stuck in eclipse (like I did), you may find yourself dropping to the command-line interfaces to see what’s really going on. However for this article, I’ll assume that you’re using the Eclipse IDE for your Android software development needs. Once you’ve downloaded the Android SDK, Eclipse and the Eclipse Plugin, you should work through the first few sections of Google’s install document (System and Software Requirements, Installing the SDK, Installing the Eclipse Plugin). I’d leave the rest of the document for later as it does get quite detailed quickly.

Read the Friendly Manual

Google has done a good job of writing a lot of documentation for Android. However, there isn’t a great way of knowing what’s important to read now vs. what can wait. Here are some links to documents that are important to understand what Android is and how to develop applications using it. If you read them in the order listed, then you’ll gain understanding more quickly as you read increasingly detailed documents. Note that a lot of the documentation is available both online and in the SDK_ROOT/docs/index.html directory on your machine. If you have a fast enough connection, I would suggest using the on-line versions since they will be more up to date.

Here’s the order in which I suggest you read the documentation:

  • What is Android? Explains what Android is and gives a high-level overview of its features and architecture. Don’t dive into the links just yet — just get a feel for this overall document.
  • Read the Anatomy of an Android Application page. This details the four building blocks of an Android app: Activity, Intent Receiver, Service and Content Provider. Again, don’t follow the links just yet — just get an overview of the architecture. You may want to reread sections on Activities and Intent Receivers — gaining an understanding of these concepts is critical to understanding how to build an Android application. If you don’t get it yet, you’ll see it again when you go through the Notepad Application Tutorial.
  • Next read the Development Tools document. Again — just get a flavor, don’t dive into the detail yet.
  • Read the Lifecycle of an Android Application page.
  • Now, finally, it’s time to get your hands dirty. Work through the Hello Android page. Make sure you actually do it using Eclipse.
Note: I had a problem here. The first time I ran the application, it worked fine. However on subsequent runs my application would not appear on the emulator. I killed and restarted the emulator, killed and restarted eclipse several times — no joy. Finally, somewhat frustrated, I was going to re-install everything. However before I did, I found an invisible instance of the Android Debug Bridge (adb) running. I killed it and everything worked again. I thought I had to close the emulator after each run of an application, but this turns out not to be the case. When I closed the emulator after my first run, it left the instance of adb running, which interfered with the subsequent instances.
  • Now go back and read the rest of the Installing the SDK document — the bottom half of it details some great debugging tips and features.
  • Next, go through the Notepad Application Tutorial. This is where the rubber really meets the road. If you spend the time to go through this series of exercises and really understand the code, you will be well on your way to becoming an Android expert.
  • Read the Developing Android Applications pages. This will take some time — these articles go into a lot of detail about several topics including how to implement the UI, data storage/retrieval and the security model.
  • Finally, go back through this list and follow the links in the previous documents as topics interest you.

There’s a lot of documentation, but if flows together nicely, reflecting the architecture of the environment.

Dissecting the SDK

Whenever I download an SDK, I like to take a look at the files I’ve installed. Often, there is a wealth of information hidden in the SDK itself that is not readily visible from the documentation. So here’s what you’ll find in the Android SDK on a Windows machine:

  • android.jar - The Android application framework. Unzipping this jar reveals the entire class structure and all of the supporting classes of the framework. Currently there is no source.
  • docs - 100 megabytes worth of documentation, samples, etc.
  • samples - Six different sample applications - ApiDemos, HelloActivity, LunarLander, NotePad, SkeletonApp and Snake
  • tools - the various SDK binaries such as aapt, acp, and emulator live here.
    • lib - various templates and supporting jar files live in this directory
      • activityCreator - the activityCreator python application lives here.
      • images - The Linux file system images are found in this directory: ramdis.img, system.img and userdata.img. They are YAFFS2 file system images, so I couldn’t open them without additional kernel support on my Fedora system.
        • skins - supporting emulator graphics for HVGA and QVGA screens in both landscape and portrait format.

Exercising the SDK

Now that you have read the documentation and set up and debugged a simple project, it’s time to look at some real code. Since Google has provided us with several sample applications, the best place to begin is by examining them.

  1. If you have not already done so, execute the first few sections of Google’s install document. Stop after you’ve installed the Eclipse plugin successfully.
  2. Now work through the Hello Android page if you haven’t already. This will get you started working with Android applications and the debugger. Note that it’s probably a good idea to create a new workspace for your Android projects if you already use Eclipse.
  3. Next we’re going to set up Eclipse projects for each of the sample applications. You can never have too much sample code. I’ll walk through setting up the Lunar Lander example and leave it as an exercise to the reader to set up the rest.
    1. Bring up the same Eclipse workspace that you used for the Hello Android, and close the project (Right click on the project in package explorer->Close Project).
    2. File->New->Android Project
    3. Project Name: LunarLander
    4. Click the “Create Project from existing source” radio button
    5. Browse to the samples/LunarLander directory in the SDK. If you find the right directory, the Properties fields will auto-fill with the correct information from the Package.
    6. Click Finish
    7. Bring up Eclipse’s Console window (Window->Show View->Console) if it’s not already visible in a tab at the bottom of the screen. It will show you the build process that Eclipse went through to create the application.
    8. Create a Run Configuration: Run->Open Run Dialog
    9. Highlight “Android Application” in the treeview to the left.
    10. Click the “New button”.
    11. Name: Lunar Lander
    12. Click the Browse button next to Project
    13. Double-click the LunarLander project and hit OK
    14. Click the down arrow for the Activity and choose the one and only Activity: com.google.android.lunarlander.LunarLander
    15. Click Apply
    16. Click Run
    17. Switch to the Emulator and play a few rounds of Lunar Lander. Kinda fun.

Repeat for the other applications in the samples directory. This exercise should only take a few minutes — besides, the Snake game is fun too! If you’ve taken the time to go through the Notepad Application Tutorial, then you’ll be familiar with the NotePad sample — however, the NotePad sample is fully developed and has features beyond the NotePad developed during the Tutorial.

A File System Explorer Application

Finally, we’ll use our new understanding of the Android to develop a simple file system explorer. The version in this article is pretty simple, but it can serve as a jumping-off point for a more serious application down the road.

Design

Before we start writing code, let’s think about what a reasonable file system browser should do. It should

  • Phase I features
    • Show a list of files and directories
    • Allow the user to navigate through the directory structure by clicking on directories
    • Warn the user that he has clicked on a file
  • Phase II features
    • Allow the user to display a dump of a file when it is clicked
    • Use a tree view instead of a simple list
    • Show a dialog box with the filesystem information (size, permissions, etc) when the user clicks on an icon next to each file
    • Give this application permissions to read any file on the file system
  • Phase III features
    • Do all of phase II with pretty graphics, such as thumbnails, instead of boring dropdowns and list boxes
    • Execute applications that we understand, such as mp3 files

Process

This article will only cover Phase I of the project — but when we’re done, we’ll have a functional file system explorer in just a few dozen lines of code.

To proceed with this hands-on example, click here.

New Android Project
(Click to enlarge)
It works!

If you clicked above to follow the hands-on example, you found that in about twenty lines of Java, and a small amount of XML, you’ve created a useful little application that will allow you to explore the Android’s file system. For example, I found the ringtones in /system/media/audio/ringtones, as shown below.


Oooh, ringtones
(Click to enlarge)

As I mentioned in the design section, a lot can be done with this application, and we’ve hardly touched the surface of what you can do with the Android application environment. There’s three billion cell phones out there. I suspect Google will get their fair share of them, so start cranking out code!

Conclusion

Android is a well-engineered development environment. Writing an Eclipse plug-in was a smart move by Google — one that should be emulated by other SDK developers. Eclipse gives a developer and environment where he can really think about the business problem without worrying about the boring details. Adding the functionality of the plugin helps developers just sit down and start coding — without having to worry about all the ins and outs of configuration files and the like.

Dislikes

Android is brand new to the general developer’s world. As I write this, it’s Wednesday, and the SDK came out on Monday of this week. Since it’s brand new, there are some little problems that will have to be solved in the coming releases.

  • Many more examples for the APIs.
  • A more thorough explanation of what does and does not work under the emulator. My first example application was a simple MP3 player.
  • Release the source code. This will make it a lot easier to debug Android applications, as well as write them in the style that the Google developers wrote them.

Likes

Theres a lot to like about Android:

  • It’s by Google — so it has a company with some clout behind it.
  • Application Developers write their code in Java. Since the learning curve for Java is much less than that of C/C++/ObjectiveC, there will be many many developers who are eager to start writing applications for Android.
  • The SDK and API are well designed. There is some complexity there, and as I mentioned, the Documentation needs improvement — but a well designed system is easier to understand and learn, even without lots of great examples.

Jun 18, 2008 Author: Ashish | Filed under: Google Android, PHP, iPhone

Advertisement

Adsense