Thursday, November 18, 2010

Basic vs Applied Research - Linear vs Nonlinear Models

I was reading a review in IEEE Spectrum of Henry Petroski's "The Essential Engineer: Why Science Alone Will Not Solve Our Global Problems", and found several references to the linear model of how research is being conducted in the U.S.:

"Part of the problem, he [Henry Petroski] says, is the linear model of technological progress: Basic research spawns applied research, which in turn fuels technological development. This model is wrong historically, and it undervalues the creative juices of good engineering ... This linear model became ascendant in U.S. science policy after 1945 when Vannevar Bush submitted his famous report, “Science—the Endless Frontier”, which enhanced the prestige (and funding) of basic research at the expense of applied work."

I wrote in one of my previous posts about linearity and nonlinearity in biology, engineering, and financial systems, and how linear models (such as blood vessels in biology, waterfall model in engineering) have a negative impact on the systems where they are applied. The review of the book has the same underlying message, namely how moving away from the linear model of basic research towards the more practical approach of applied research (or development projects) has a greater outcome in terms of engineering advances. 

Wednesday, November 17, 2010

Android Ginerbread adds NFC support

Listening to the conversation with Eric Schmidt at the Web 2.0 Summit 2010, I was pleasantly surprised that the new Android 2.3 (called "Gingerbread"), will add support for NFC, or Near Field Communication (I heard rumors about this in the past). There are many use cases that I can think of, the major one being using your phone for making payments. I said it in the past that the main reason I think NFC has not been adopted is because there was no major company/platform using it. Now there is.

Tuesday, October 26, 2010

2010 Gadget Census

Retrevo's 2010 Gadget Census revealed what gadgets people were using in each state, with the summary of it captured in the image below:

Tuesday, September 21, 2010

Articulated Naturality Web

Articulated Naturality Web, or ANW, is what comes after augmented reality, the next level, the next phase if you will. There's a short video posted on engadget (and at the end of this blog post) that shows some of the features of ANW. For me, it's amazing because it fuses sensors, location, internet, image processing, and much more into one technology that gives meaning to the surroundings by means of your smartphone. Imagine sitting outside of an hotel, and looking at the available rooms, how they look inside, prices, and booking information. Blows my mind what we can achieve today with the amount of information and the technology available to us.

Thursday, August 26, 2010

Installing iPhone/iPad application ad-hoc

At my current job, I had to remotely install some beta versions of the iPad app for some clients, before the app was actually released on iTunes. There are several steps that one has to take in order to achieve that (assuming you have followed some of them that describe creating Certificates, App IDs, etc):
  1. In your iPhone Developer account, go to the iPhone Provisioning Portal, the to Devices, and add the iPad device to the Current Registered Devices section. You have to know the Device UDID (40 characters that can be copied form iTunes when you have the iPad plugged into your computer).
  2. Add the newly created device to the Distribution Provisioning Profile. 
  3. On you station, drag-and-drop the distributed provisioning profile into XCode. 
  4. Under XCode, change both your app's and your target's build properties to use the new distribution provisioning profile. 
  5. Delete the old Entitlements.plist file and create a new one.
  6. Change your settings so that XCode uses Device as the Active SDK, and Distribution as the Active Configuration. 
  7. Build your app, then zip the executable. 
  8. Export your private key and the developer identity certificate and import them into your client's Keychain (you might also need to export-import the AppleWWDRCA.cer file to your client). Finally, add the iPhone distribution certificate to the Keychain. 
  9. Download the new distributed provisioning profile and drag-and-drop it into your customer's iTunes app (either drop it on the iTunes icon, or in the App section). 
  10. Un-zip your application and drag-and-drop it into the app section of your customer iTunes (if the Apps section is not visible, go into iTunes -> Preferences and click on the checkbox marked as Apps). 
  11. Synchronize iTunes with the iPad to transfer the app from iTunes to your client's iPad. 
Hope it's going to help some of you. Enjoy!

Sunday, July 4, 2010

Saturday, May 29, 2010

Robots: they re-arrange themselves and officiate a marriage ceremony

Yukiko Sawada and Takashi Tsubouchi at the University of Tsukuba, Japan, have built a self-configuring conference room, where the tables are robots that re-arrange themselves based on an initial configuration inputed through a User Interface:



And, if we are on the subject of robots, also in Japan, a robot named i-Fairy officiated a marriage ceremony:

Tuesday, May 4, 2010

Mobile Monday Miami - May 2010

Yesterday evening I attended my first Mobile Monday Miami meeting. It was a breath of fresh air to meet and connect with people that share the same interest as I do, and are enthusiastic about anything and everything mobile. The topic was "Will The Mobile Web Kill Off The App Store?" The overall conclusion was that whether you develop your app on the mobile browser or natively, it really depends on the uses case you have at hand. Let's look at some pros and cons of both approaches:
  • Mobile Web
    • PROS: One app for all platforms (almost). With the adoption of WebKit (iPhone, Android, WebOS, Nokia, and soon RIM) and HTML 5, this could become the cross-platform solution that everyone is searching for.
    • CONS: Getting access to some low level functionality of the phone is very difficult. Could you query the phone's proximity sensor for example? Not really. 
  • Native
    • PROS: Full access to the phone's APIs that provide you a way to query its hardware.
    • CONS: Having to develop one app for each platform. There are cross-platform tools that try to mitigate this issue. I haven't used any of those tools, although I wrote about them, but the comment made by Steve Jobs that the platforms will support the lowest common denominator in terms of features. However, I imagine that you could tweak the tools to take advantage of the features provided by every platform that you target.
Another view of the topic discussed Monday was the benefit of having an App Store in terms of discoverability and distribution, a one stop place. This can never be achieved with a web version.

Overall, fantastic discussions, great turnout, I'll definitely become a regular. 

Friday, April 30, 2010

BlackBerry in Top 5 of Worldwide Mobile Phone Bestsellers

As per wired.com, RIM has replaced Motorola in the top five mobile phone companies worldwide based on Q1 2010 sales, and it's tied with Sony Ericsson for the number 4 spot:


This is not unexpected since when it comes to enterprise and messaging, there is nothing like the BlackBerry. On a side note, Motorola has actually had profit for the first quarter of 2010, earning $69 millions. Go Moto!

Sunday, April 25, 2010

Ten Best Chapters of Software Development Books

I have file on my laptop that contains a huge list of books (mostly software related) that I just don't have the time to read completely, or to read at all (but I do have time to write this blog :)). Beside the list of books, the file has links to other lists of books of the type "every programmer should read", "must read", you got the idea. Dustin Marx came up with his own list, but what is different is that it gives you a list of best chapters of software development books, chapters that he "found to be most influential or most impressive" in his career as a software developer. If you're just like me, you will appreciate the list.

Saturday, April 24, 2010

The Marshmallow Challenge

Tom Wujec conducted a team building experiment called the marshmallow challenge with people ranging from kindergartners to CEOs, with results that were surprising. His presentation is below:

Monday, April 12, 2010

Perfect Mobile Platform

What would make up the perfect mobile platform? What characteristics should it posses? Here are some of them, in no specific order:
  • User Interface/Experience - a rich user interface that provides a great user experience. When using the phone, everything should come naturally, with ease, and should have the WOW factor that makes you never want to leave the phone out of your hands. Doing common tasks should not take more than a few clicks. 
  • Application Ecosystem - Having many applications to chose from is not as important as having quality applications, those that satisfy a particular need, like finding a place to eat, checking your email, or playing Doom. Integrating location, social networking, and sensors is a must.
  • Internet Browsing - surf the Web from anywhere, on the go. A mobile browser should be able to render pages properly and fast, navigation should be done with ease, data should be compressed as to save bandwidth, and use the latest web technologies (HTML5, CSS, JavaScript, etc).
  • Battery Life - it better not leave me hanging after a full day of use, or in the middle of a call, or while searching for a place to eat using the GPS. 
  • Development Ecosystem - provide a rich set of APIs that can access all the features of the phone, and can provide the best user experience. Provide tools that can be used to make it easier to write apps. Publishing an application should not involve much hassle. 
  • Openness - here I refer to not only an open and free platform, but to a platform that allows any mobile technology to work on it.
  • Enterprise - features such as security, integration with email/calendar/notes/contacts servers, messaging, to name just a few. 
There is no one platform that satisfies all these needs better than any other platform. What is needed is a platform that has the user experience of iPhone and Android, the application ecosystem of iPhone (and Android very soon), the internet browsing of iPhone and Android (mostly any WebKit-based browsers), the battery life of the Blackberry, the development ecosystem of Android and iPhone, the openness of Android, and the enterprise characteristics of Blackberry. 

Will we ever have such a platform? I really doubt it. 

Thursday, April 8, 2010

Smartphone Application Downloads Forecast

ABI Research has recently published a forecast for smartphone application downloads world wide for 2009 - 2015, and which can bee seen in the chart below:


While iPhone apps are still going to be the leading source of downloads, for the year of 2010, Android is expected to have over 800 millions application downloaded, a major increase compared to 2009. Beside iPhone and Android, Blackberry and Symbian are also catching up on sales. What all this means, at least for me, is that it is a great time to be a mobile developer :)

Monday, April 5, 2010

We will live in a game

"We will live in a game!" This is what you will take away after watching Jesse Schell's presentation at DICE 2010 summit. He envisions a day that has normal activities, like brushing your teeth, eating cereals, watch TV, etc, but which will let you win points and benefits when attending to those activities.

Great fun to watch the presentation, very intriguing and eye opening at the same time. Read about it via IEEE Spectrum.

Wednesday, March 3, 2010

Battery Information using iPhone's Cocoa Touch

I have done something similar (although on a smaller scale) to this but for the Android platform. For the iPhone platform, the main class used is UIDevice. Below is the header used:
#import <UIKit/UIKit.h>


@interface BatteryInformationViewController : UIViewController {
    IBOutlet UITextView *batteryLevel;
    IBOutlet UITextView *chargingState;
    // Used to format the battery level
    NSNumberFormatter *numberFormatter; 
}

@property (nonatomic, retain) UITextView *batteryLevel;
@property (nonatomic, retain) UITextView *chargingState;
@property (nonatomic, retain, readonly) NSNumberFormatter *numberFormatter;

@end 
There are two UI elements (text views), namely the battery level and the battery charging state. The corresponding implementation file is next:
#import "BatteryInformationViewController.h"

@interface BatteryInformationViewController ()

- (void)displayBatteryLevel;
- (void)displayBatteryStatus;

@end

@implementation BatteryInformationViewController

@synthesize batteryLevel, chargingState;


- (NSNumberFormatter *)numberFormatter
{
    if (numberFormatter == nil)
    {
        // Used for formatting the battery level
        numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setNumberStyle:NSNumberFormatterPercentStyle];
        [numberFormatter setMaximumFractionDigits:1];
    }
    return numberFormatter;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Register for battery level and state change notifications.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(batteryLevelDidChange:)
                                                 name:UIDeviceBatteryLevelDidChangeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(batteryStateDidChange:)
                                                 name:UIDeviceBatteryStateDidChangeNotification object:nil];
    
    [self displayBatteryLevel];
    
    [self displayBatteryStatus];
    
}

#pragma mark Battery Info

- (void)displayBatteryLevel {
    float batteryLevelLocal = [UIDevice currentDevice].batteryLevel;
    if (batteryLevelLocal < 0.0)
    {
        // -1.0 means battery state is UIDeviceBatteryStateUnknown
        self.batteryLevel.text = NSLocalizedString(@"Unknown", @"");
    }
    else {
        NSNumber *levelObj = [NSNumber numberWithFloat:batteryLevelLocal];
        
        // Using the numberFormatter property lazily creates that object the
        // first time it's used. 
        self.batteryLevel.text = [self.numberFormatter stringFromNumber:levelObj];
    }    
}

- (void)displayBatteryStatus {
    // Get battery state
    switch ([UIDevice currentDevice].batteryState) {
        case UIDeviceBatteryStateUnknown:
        {
            self.chargingState.text = NSLocalizedString(@"Unknown", @"");
            break;
        }
        case UIDeviceBatteryStateUnplugged:
        {
            self.chargingState.text = NSLocalizedString(@"Unplugged", @"");
            break;
        }
        case UIDeviceBatteryStateCharging:
        {
            self.chargingState.text = NSLocalizedString(@"Charging", @"");
            break;
        }
        case UIDeviceBatteryStateFull:
        {
            self.chargingState.text = NSLocalizedString(@"Full", @"");
            break;
        }
    }    
}

#pragma mark Battery Notifications

// Called when the battery level has changed
- (void)batteryLevelDidChange:(NSNotification *)notification
{
    [self displayBatteryLevel];
}

// Clalled when the battery status has changed
- (void)batteryStateDidChange:(NSNotification *)notification
{
    [self displayBatteryStatus];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.batteryLevel = nil;
    self.chargingState = nil;
}

- (void)viewDidDisappear:(BOOL)animated {
    [[NSUserDefaults standardUserDefaults] setInteger:2 forKey:@"WhichView"];
}


- (void)dealloc {
    [batteryLevel release];
    [chargingState release];
    [numberFormatter release];
    [super dealloc];
}


@end 
The above code is commented, so it should be pretty obvious what it does. I first register for change notifications for battery level and battery status change, and display the initial values for those properties.

There is a really good example from Apple called BatteryStatus. It should give you anything you need regarding battery information.

I hope you find it useful!

Monday, February 8, 2010

Android XML Parsing

If you ever considered which parser to use in Android, on developer.com you can find an article that does a comparison of DOM, SAX, and XMLPullParser. Since I started working with Java ME in 2003, SAX was the XML parser of choice, since DOM consumed to much memory and was slower. Nothing changed in Android, although the pull parser is much closer in performance to SAX.

Sunday, February 7, 2010

Getting the Battery Level in Android using the SDK

Finding out the battery level using the Android SDK is not quite an easy task because this functionality is not documented, which means it can change at any point in time. Well, after reading a little more about the ACTION_BATTERY_CHANGED Intent and about the BatteryManager class, starting with API Level 5, you have all the information needed to get the status on your phone's battery. The BatteryManager class contains some String values that will give you information about the current battery level and the scale, constants such as EXTRA_LEVEL and EXTRA_SCALE. If you were to work with an API version older than 2.0 (< 5), then it becomes a little more difficult to find the right information as it is not documented in the APIs as far as I could tell.

For now, here is how you can find out:
  • Create an IntentFilter that matches the Intent.ACTION_BATTERY_CHANGED action.
  • Create a BroadcastReceiver that will be called with a broadcast intent.
  • Inside onReceive, retrieve data based on the "level" item (battery level) for version < 5, or use BatteryManager.EXTRA_LEVEL for versions >= 5.
  • Register the receiver that will be called with the broadcast intent that signals a battery change 
Here is the BatteryLevelActivity:
package edu.fau.csi.battery;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;

/**
 * Used for finding the battery level of an Android-based phone.
 * 
 * @author Mihai Fonoage
 *
 */
public class BatteryLevelActivity extends Activity {
    /** Called when the activity is first created. */
    private TextView batterLevel;

    @Override
    /**
     * Called when the current activity is first created.
     */
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        batterLevel = (TextView) this.findViewById(R.id.batteryLevel);
        batteryLevel();
    }

    /**
     * Computes the battery level by registering a receiver to the intent triggered 
     * by a battery status/level change.
     */
    private void batteryLevel() {
        BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                context.unregisterReceiver(this);
                int rawlevel = intent.getIntExtra("level", -1);
                int scale = intent.getIntExtra("scale", -1);
                int level = -1;
                if (rawlevel >= 0 && scale > 0) {
                    level = (rawlevel * 100) / scale;
                }
                batterLevel.setText("Battery Level Remaining: " + level + "%");
            }
        };
        IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryLevelReceiver, batteryLevelFilter);
    }
    
}
The battery.xml layout file is next:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
  xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent"> 
  
    <TextView         
        android:id="@+id/batteryLevel"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:gravity="center_vertical|center_horizontal"
        android:textSize="50dip"> 
    </TextView>
    
</LinearLayout>


As I mentioned in the beginning, if you are using Android 2.0 or higher, you can make the following changes to the batteryLevel method of the BatterLevelActivity class:
    /**
     * Computes the battery level by registering a receiver to the intent triggered 
     * by a battery status/level change.
     */
    private void batteryLevel() {
        BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                context.unregisterReceiver(this);
                int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                int level = -1;
                if (rawlevel >= 0 && scale > 0) {
                    level = (rawlevel * 100) / scale;
                }
                batterLevel.setText("Battery Level Remaining: " + level + "%");
            }
        };
        IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryLevelReceiver, batteryLevelFilter);
    }
The code for getting the battery level was inspired from the Twisty project.

Enjoy!

Sunday, January 31, 2010

Unit and Functional Testing in Android

I don't have to tell you that testing is a fundamental part of the product development cycle, although I just did. No matter if you are developing for the desktop, web, or mobile space, you should make sure that the end software system works as required. This blog will go through two flavors of testing on the Android platform: unit and functional.

Unit tests tell the developer that the code runs correctly, while functional tests tell the developer that the code is doing what is supposed to do. To more clearly understand the difference, I will use the analogy mentioned in http://www.ibm.com/developerworks/library/j-test.html. If you think of building a system as being similar to building a house, then think of unit tests as having the building inspector at the construction's site, focusing on making sure that the internal system of the house (foundation, plumbing, etc) works correctly, while functional testing as having the homeowner visiting the house and being interested in how the house looks, if the rooms have the desired size, etc. He assumes that the internal functions of the house work properly.

In unit testing, think of a unit as being the smallest testable part of an application, such as a function/method. The goal is to isolate such parts and make sure they run correctly by being able to test them repeatably. Unit tests are written from the developer's perspective, and as a developer, we have to make sure that we understand the specification and requirements of our software system before writing unit tests. This can be achieved through use cases.

The flow of unit testing is shown below:


Android uses JUnit, and open source framework for writing and running unit tests. Some of the framework's features are:
  • Assertions for testing expected results
  • Test fixtures for sharing common data
  • Test runners for running tests
How does JUnit work? You use assert statements to assert that something is true (assertTrue(expected, actual), assertTrue(condition), etc), that something is false (assertFalse(condition), etc), that something is equal (assertEqual(expected, actual), etc). When an assert fails, the test failed for that particular case, hence your code needs to be fixed (assuming the unit test was written correctly). 

Starting with version 4.x, JUnit takes advantage of Java 5 Annotations:

  • @Test
    • Mark your test cases with the @Test annotation
  • @Before and @After
    • Used for "setup" and "tearDown" methods
    • They run before and after every test case
  • @BeforeClass and @AfterClass
    • Used for class wide "setup" and "tearDown"
    • They run one time, before and after all test cases
    • You write you initialization code (i.e. open database connection) and cleanup code (i.e. close database connection) in here
  • @Ignore
    • Used for test cases you want to ignore (i.e. on methods that are not fully implemented yet, hence are not ready to be ran)
  • Exception Handling
    • Use the "expected" parameter with the @Test annotation for test cases that expect exceptions (i.e. @Test(expected = ArithmeticException.class) ...
Let us look at a Java Example, namely a Calculator application. The class that incorporates the basic functionality of a calculator is shown below:

/**
package edu.fau.csi.junit;

/**
 * Simple class that incorporates the basic functionality of a calculator, providing methods to 
 * add, subtract, multiply, and divide to double numbers.  
 * 
 * @author Mihai Fonoage
 *
 */
public class Calculator {
    /**
     * Left operand of the operation to be performed.
     */
    private double leftOperand;
    /**
     * Right operand of the operation to be performed.
     */
    private double rightOperand;
    
    /**
     * Constructs a Calculator object by initializing the leftOperand and rightOperand 
     * with the given values.
     * 
     * @param leftOperand Left operand.
     * @param rightOperand Right operand.
     */
    public Calculator(double leftOperand, double rightOperand) {
        this.leftOperand = leftOperand;
        this.rightOperand = rightOperand;
    }
    
    /**
     * Adds the leftOperand to the rightOperand.
     * 
     * @return The sum of the two operands. 
     */
    public double add() {
        return leftOperand + rightOperand;
    }
    /**
     * Subtracts the rightOperand from the leftOperand.
     * 
     * @return The subtraction of the two operands. 
     */
    public double subtract() {
        return leftOperand - rightOperand;
    }
    /**
     * Multiply the leftOperand to the rightOperand.
     * 
     * @return The multiplication of the two operands. 
     */
    public double multiply() {
        return leftOperand * rightOperand;
    }
    /**
     * Divides the leftOperand to the rightOperand.
     * 
     * @return The division of the two operands. 
     */
    public double divide() {
        if (rightOperand == 0) {
            throw new ArithmeticException("right operand should not be zero!");
        }
        return leftOperand / rightOperand;
    }
}
I created a new source folder named test and included the following test class (by right-clicking on the project name -> New -> JUnit Test Case, choose "New JUnit 4 test", and as the class under test, search for the above Calculator class):
package edu.fau.csi.junit;

import static org.junit.Assert.assertTrue;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * JUnit Test case for the Calculator class.
 * 
 * @author Mihai Fonoage
 *
 */
public class CalculatorTest {
    
    private Calculator calculator;
    
    /**
     * Sets up the test fixture. 
     * (Called before every test case method.)
     */
    @Before
    public void setUp() {
        calculator = new Calculator(6, 4);
    }

    /**
     * Tears down the test fixture. 
     * (Called after every test case method.)
     */
    @After
    public void tearDown() {
        calculator = null;
    }

    /**
     * Test method for {@link edu.fau.csi.junit.Calculator#add()}.
     */
    @Test
    public void testAdd() {
        assertTrue(calculator.add() == 10);
    }

    /**
     * Test method for {@link edu.fau.csi.junit.Calculator#subtract()}.
     */
    @Test
    public void testSubtract() {
        assertTrue(calculator.subtract() == 2);
    }

    /**
     * Test method for {@link edu.fau.csi.junit.Calculator#multiply()}.
     */
    @Test
    public void testMultiply() {        
        assertTrue(calculator.multiply() == 24);
    }
    
    /**
     * Test method for {@link edu.fau.csi.junit.Calculator#divide()}.
     */
    @Test
    public void testDivide() {
        assertTrue(calculator.divide() == 1.5);
    }

    /**
     * Test method for {@link edu.fau.csi.junit.Calculator#divide()}.
     */
    @Test(expected = ArithmeticException.class)
    public void testDivideByZero() {
        Calculator calculator = new Calculator(6, 0);
        calculator.divide();
    }

}
To run everything, right-click on the CalculatorTest class -> Run As -> JUnit Test. All five tests should pass.

Functional tests are written from the user's perspective. They confirm that the system does what the user expected it to do, based on the functional requirements of the system, hence it focuses on the behavior that users are interested in. The tester interacts with the system to determine if the behavior is correct.

In Android, functional testing is possible through the android.test.* package(s). We are going to use the same Calculator example, adapted for Android. When you create the Calculator Android project in Eclipse, choose also co create a Test Project for it. You will end up with two project, the Calculator project and the CalculatorTest project. The layout of the Calculator project is described below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/linear" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical">
    
    <TableLayout android:id="@+id/table" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" 
        android:stretchColumns="1">
        <TableRow>
            <TextView android:id="@+id/leftOperand_label" 
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" 
                android:padding="3dip"
                android:textStyle="bold" 
                android:text="Left Operand">
            </TextView>
            <EditText android:id="@+id/leftOperand" 
                android:padding="3dip"
                android:numeric="decimal"
                android:singleLine="true"
                android:scrollHorizontally="true" 
                android:nextFocusDown="@+id/rightOperand">
            </EditText>
        </TableRow>
        <TableRow>
            <TextView android:id="@+id/rightOperand_label" 
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" 
                android:padding="3dip"
                android:textStyle="bold" 
                android:text="Right Operand">
            </TextView>
            <EditText android:id="@+id/rightOperand" 
                android:padding="3dip"
                android:singleLine="true"
                android:scrollHorizontally="true"
                android:nextFocusDown="@+id/plus">
            </EditText>
        </TableRow>
    </TableLayout>
    
    <LinearLayout android:id="@+id/buttons_linear" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        
        <Button android:id="@+id/plus" 
            android:layout_width="0px"
            android:layout_height="wrap_content" 
            android:layout_weight="1"
            android:padding="6dip"
            android:text="+" 
            android:layout_gravity="center_horizontal" 
            android:nextFocusRight="@+id/minus">
        </Button>
        
        <Button android:id="@+id/minus" 
            android:layout_width="0px"
            android:layout_height="wrap_content" 
            android:layout_weight="1"
            android:padding="6dip"
            android:text="-" 
            android:layout_gravity="center_horizontal" 
            android:nextFocusRight="@+id/multiply">
        </Button>
        
        <Button android:id="@+id/multiply" 
            android:layout_width="0px"
            android:layout_height="wrap_content" 
            android:layout_weight="1"
            android:padding="6dip"
            android:text="*" 
            android:layout_gravity="center_horizontal" 
            android:nextFocusRight="@+id/divide">
        </Button>
        
        <Button android:id="@+id/divide" 
            android:layout_width="0px"
            android:layout_height="wrap_content" 
            android:layout_weight="1"
            android:padding="6dip"
            android:text="/" 
            android:layout_gravity="center_horizontal" 
            android:nextFocusRight="@+id/divide">
        </Button>
        
        <Button android:id="@+id/clear" 
            android:layout_width="0px"
            android:layout_height="wrap_content" 
            android:layout_weight="1"
            android:padding="6dip"
            android:text="C" 
            android:layout_gravity="center_horizontal" 
            android:nextFocusRight="@+id/divide">
        </Button>
        
    </LinearLayout>
    
    <TextView android:id="@+id/result" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:padding="20dip"
        android:textStyle="bold" 
        android:gravity="right"
        android:text="Result">
    </TextView>
    
</LinearLayout>

It is a simple layout, with two initial text fields for the left and right operand, five buttons, each for one operation, plus a clear button, and one text field that will hold the result of the calculation. As a side note, I have put the text for each of these elements inside the layout xml file to save some time; you should put them inside the strings.xml file instead.

The CalculatorActivity class is described next:

package edu.fau.csi.calculator;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class CalculatorActivity extends Activity implements OnClickListener {

    private EditText leftOperand;

    private EditText rightOperand;

    private TextView result;
    
    private Calculator calculator;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calculator);
                        
        leftOperand = (EditText)findViewById(R.id.leftOperand);
        rightOperand = (EditText)findViewById(R.id.rightOperand);
        result = (TextView)findViewById(R.id.result);

        Button plus = (Button)findViewById(R.id.plus);
        plus.setOnClickListener(this);
        Button minus = (Button)findViewById(R.id.minus);
        minus.setOnClickListener(this);
        Button multiply = (Button)findViewById(R.id.multiply);
        multiply.setOnClickListener(this);
        Button divide = (Button)findViewById(R.id.divide);
        divide.setOnClickListener(this);
        Button clear = (Button)findViewById(R.id.clear);
        clear.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        double leftOp = Double.parseDouble(leftOperand.getText().toString());
        double rightOp = Double.parseDouble(rightOperand.getText().toString());
        calculator = new Calculator(leftOp, rightOp);
        
        if (view.getId() == R.id.plus) {
            result.setText("" + calculator.add());
        }
        else if (view.getId() == R.id.minus) {
            result.setText("" + calculator.add());
        }
        else if (view.getId() == R.id.multiply) {
            result.setText("" + calculator.multiply());
        }
        else if (view.getId() == R.id.divide) {
            result.setText("" + calculator.divide());
        }
        else if (view.getId() == R.id.clear) {
            leftOperand.setText("");
            rightOperand.setText("");
            result.setText("");
            leftOperand.requestFocus();
        }
    }
}

The Calculator class that actually does the calculations is exactly the same as the one from the Java example.

When you run this example, you will get the following screen:

The unit testing part is the same as the one mentioned in the unit testing section of this blog. You can still test your business logic without needing to interact with the application through its user interface. Actually, Calculator.java and CalculatorTest.java were just copied from the Java example to the Android without making any modifications.

Functional testing for this example involves the process of entering numbers in the two text fields, pressing one of the operations button, and checking the result to make sure it is the expected one. Instead of having the developer/user/tester do this manually, we can automate the task by sending key events through instrumentation, all from the CalculatorActivityTest class from the CalculatorTest application:
package edu.fau.csi.calculator.test;

import android.test.ActivityInstrumentationTestCase2;
import android.view.KeyEvent;
import android.widget.TextView;
import edu.fau.csi.calculator.CalculatorActivity;


public class CalculatorActivityTest extends ActivityInstrumentationTestCase2<CalculatorActivity>{

    private TextView result;

    private CalculatorActivity calculatorInstance;

    public CalculatorActivityTest() {
        super("edu.fau.csi.calculator", CalculatorActivity.class);
    }

    /* (non-Javadoc)
     * @see android.test.ActivityInstrumentationTestCase2#setUp()
     */
    @Override
    protected void setUp() throws Exception {
        // TODO Auto-generated method stub
        super.setUp();
        calculatorInstance = (CalculatorActivity) getActivity();
        result = (TextView)calculatorInstance.findViewById(R.id.result);
    
    }

    /**
     * Test the addition operation of the CalculatorActivity
     * 
     * @throws Throwable
     */
    public void testAdd() throws Throwable {
        
        //First field value
        sendKeys( KeyEvent.KEYCODE_3 );
        sendKeys( KeyEvent.KEYCODE_PERIOD );
        sendKeys( KeyEvent.KEYCODE_5 );
        
        //Move to the second field
        sendKeys( KeyEvent.KEYCODE_DPAD_DOWN );
        sendKeys( KeyEvent.KEYCODE_2 );
        sendKeys( KeyEvent.KEYCODE_PERIOD );
        sendKeys( KeyEvent.KEYCODE_1 );

        //Move to the '+' button
        sendKeys( KeyEvent.KEYCODE_DPAD_DOWN );
        sendKeys( KeyEvent.KEYCODE_DPAD_CENTER );

        //Wait for the activity to finish all of its processing.
        getInstrumentation().waitForIdleSync();
        
        //Use assertion to make sure the value is correct
        assertTrue(result.getText().toString().equals("5.6"));
        
    } 
}

The above activity test class inherits from the ActivityInstrumentationTestCase2 that provides functional testing of a single activity, namely our CalculatorActivity. The above code only tests the add method, but similar implementations can be done for all other three calculations.

The Android manifest file for the CalculatorTest project is described next:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="edu.fau.csi.calculator.test"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">

    <uses-library android:name="android.test.runner" />
    </application>
    <uses-sdk android:minSdkVersion="4" />
    <instrumentation android:targetPackage="edu.fau.csi.calculator" 
        android:name="android.test.InstrumentationTestRunner" />
</manifest>

When the activity is ran for the first time, you have to create a new Android JUnit Test configuration. There are two possibilities, both shown below:

 or


When you run this, the Calculator application will start in the emulator, you will see the two text fields being populated with the values 3.5 and 2.1, the "+" button being pressed, and the result field populated with the result of the operation, namely 5.6.

I hope you find this helpful!

Tuesday, January 12, 2010

Are students prepared for working in the industry?

This should have actually been a two-part blog, first talk about the fact that there are now course on iPhone and Android programming offered at my university, and second transition to the topic mentioned in the title of the blog, namely the existing gap between what we are thought in school, and what is actually needed outside in the industry. Just by the fact that such courses are being offered, I believe that the gap is getting a little smaller. Read on to get a feel of what I think about all this.

I had my first lecture as part of the iPhone Programming class offered at FAU (similar to the course offered at Stanford and available online for free) I am excited because mobile development has been a passion of mine for some time now. I have been working with J2ME since my fourth year of college (2004), and with Android since before its official 1.0 release. Both platforms come with their advantages and shortcomings. Now, the opportunity to take part of the iPhone class could not be left unanswered, hence I enrolled for the Spring semester as part of my last class moving toward the end of my PhD.

I wanted to look into iPhone programming for some time now, but there were some impediments like not owning a Mac, and not having time for it. Well, my first problem was solved because, graciously enough, our CEECS department at FAU has created an advanced Apple Lab that comes with 10 Macs and 5 iPod Touch. My second problem got solved due to the fact that I had to take one more class, so why not make it one that is all about mobile programming. At the end of the class, I could better compare and contrast the different mobile platforms that I am familiar with.

I had some (minor) complaints about the curricula here at FAU. I felt that the courses being thought are somewhat out of touch with the need of the industry. And because most of the students end up working in the industry, better choices for courses could be offered. I have a whole list of classes that I wish would be offered here, and I am going to share this with list with you (letting me know what other classes you think would be useful):
  • Web Services (SOA more generally)
  • Software Testing (Black/White Box, Integration/Regression/Acceptance/Unit Testing, TDD)
  • Java and C# (and here maybe more on the Enterprise side with Java EE and .NET)
  • Compilers
  • Project Management (Lean, Agile (XP, Scrum), RUP, V-MODEL)
  • Functional and Logical Programming
  • Distributed Systems
  • Math for Computer Science
  • Web Developemnt (in terms of Rails, PhP, Flash, Perl, Python, GWT)
  • Software Security (Encryption, SSL/TSL, HTTPS, Cyphers, Hashes, etc)
Mobile Development class that would include Java ME, Android, and iPhone Programming, was also on the list but fortunately enough, Android and iPhone Programming are currently being taught here at FAU (I am much involved in the Android class, not as a student, but as a teaching assistant). Refactoring was also on the list, but having a whole class on this topic seems a little too much (instead it could be incorporated in any programming class available).

I recently read an article written by Bjarne Stroustrup entitled "What Should We Teach New Software Developers? Why", that expressed some of the feelings I have on this topic. Although there is still room for improvement, I do believe that we (FAU, but I am sure some universities were already on this path for some time) are going in the right direction offering courses that are useful when graduating from school.

Tuesday, January 5, 2010

Must-Read Software Development Resources for 2009

At the end of last year, Dustin Marx wrote a blog about the Must-Read Software Development Resources for 2009, where he mentions useful blogs and articles for software developers. You'll find information ranging from discussion on simplicity to the existing gap between academia and industry (article written by Stroustrup, and the one I found most interesting of all).

If you find yourself wanting more, the last two links are to other ten papers that "every programmer should read", and you should read them as they are really insightful.