Wednesday 9 February 2011

Part 3: TipCalc Sample

Index:
1. First dabble with Google Android
2. That Sample
3. TipCalc Sample

After my previous post I continued working on this sample Andriod application. One very important thing that I found was that the need for "adb" (step 4/5 in the previous post) seems redundant, at least in relation to this specific sample. Intead, in step 4, Apache Ant can be used to compile, install, uninstall and recompile the application as needed. Simply use one of the and parameters, for example, "ant install", "ant uninstall" etc. This seems to emulate the compile and adb install from the previous post.

Now let us continue on the actual TipCalc application, as defined in the sample blog. I started by playing around with DroidDraw a little, but it soon became clear that this application was used to generate the form xml needed to define the front end interface. I will write another blog entry on the use and usefulness of DroidDraw in the near future. But for now, I simply followed instructions as stated in the sample blog. This can be summarised in 3 steps:

  1. Uninstall the Hello World application. The short way to do this is simply by typing "ant uninstall" from the /tipcalc directory

  2. Update the main.xml form. This was reasonably straight forward.

  3. Update the main.java file. This needed a little bit of adjustment. Firstly, the package import on the first line reads "package com.android", this is clearly not the package name specified in the original create project command, I needed to change this to "package com.android.tipcalc". Secondly, because I ran multiple tests, my project name was actually tipcalc5, so the package needed to be com.android.tipcalc5 AND my classname in the file should have also been changed to tipcalc5. This may not affect anyone else, depending on your structure. Either way, these issues should be easy to track down using the output from the "ant compile" or "ant install" commands, e.g.



After running "ant install" again, the application installed without any issues. I was able to run it directly from the emulator.

Let's now look at the actual code a little. I am only going to focus on the java code for now. I do this for no other reason than I easily understand what is happening here. I have some (although limited) Java experience, the majority of my coding experience is in C#. But still, you know one OOB language, you know them all... right? Time will tell. For all you Java buffs out there, feel free to correct me. Also, note that the target audience to this blog post may not necessarily be senior developers, although I am not going into the extreme basics, I will be breaking things down into reasonably basic steps, it is an easy sample after all.

Disclaimer: This is not my source code. I do not have permission to reproduce it in any way, shape or form. This blog entry is intended as supplementary material to this blog. I will remove the source code from my blog if I am requested to do so by the owner of the source blog or any of its affiliates. Any other comments and ideas on this blog are my own.

Firstly the application loads all the libraries needed to run. These will vary based on what you are trying to achieve. The first 2 imports are the core libraries needed to create an activity in Android; the other 4 are used to access textfields, buttons, etc.

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

Next, all the global variables are created. I do notice that all variables in this application are global. It would be interesting to know what effect this will have on memory usage on an Android device. I assume that the focus of mobile device applications will be to keep things lightweight in every aspect, including memory usage, battery (cpu) usage and disk cost. I am sure some future experiments will answer these questions for me. Here’s an extract of the global variable declaration:

private EditText txtbillamount;
private EditText txtpeople;
......
private double tipamount = 0;
private double totaltopay = 0;
private double perperson = 0;


This is now where things get a little interesting. The method for entering into an Android Application (based purely on this application) is the overridden OnCreate method. This method calls the base OnCreate class (the one it is overriding) and then the ContentView initialisation method. This method then reads the information in the main.xml file (as updated manually earlier). The “default” java file only contains these two lines, so it is clear that this should be the starting (entry) point into your application. The tipcalc application then adds a call to the method that initialises the controls on the form.

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}


Now it gets really interesting. I had to go and delve into the main.xml file. Let me show the xml and the java for the calculate button now:


Button android:id="@+id/btncalculate" android:layout_width="87px" android:layout_height="wrap_content" android:text="Calculate" android:layout_x="40px" android:layout_y="182px"

btncalculate = (Button)findViewById(R.id.btncalculate);

From above it can be seen that the objects (button in this example) can be referenced using the android:id xml attribute for each xml element. This is stored as a static object inside the “R” object. I have not played around with this enough to fully understand this “R” object yet, but it is clear that it is the representation of the values in the main.xml file. I would also bet that this “R” object gets initialised during the setContentView(R.layout.main) method call in the onCreate method (probably stating the obvious though). The other attributes on this button (text, layout_x, layout_y) would be accessible via the btncalculate variable. Each of the objects get initialised in the rest of the init method.

Next the onclick events need to be initialised

btncalculate.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ calculate(); }});

Each button needs to be given something to do when it is clicked. The above line pretty much says that the calculate() method will be called when the button is clicked. It would be interesting to see what other events can be triggered from each object type. It would also be interesting to see what is inside the “View” input parameter of the onClick method that is defined, but all that will wait for another day.

Finally, there are two methods, calculate() and reset(), each called by pressing the corresponding button. The calculate button does the calculations and the reset does the reset (wow, stating the obvious). The actual code in these two methods are pretty straight forward, some basic casting, which seems fairly universal across several programming languages.

So in conclusion, my intention was to learn some basics of Android development. This sample gave me a big kick-start in writing my own application. Things like how to access the front end objects, how to enter into the application and how to run it on the emulator has been extremely helpful. Also, putting what I’ve learned in blog form, as I am learning it, has helped me think about these things in greater depth. Question is now, do I continue on with some more samples first, or do I start writing my own stuff? I think I will work with what I know already and at least see if I can write some of my own stuff. The hardest thing to do is to think of a useful idea that is not a rip-off of another application already available in the Android Market Place. Well, I guess it is about what your intention is, mine is to learn first of all. Learning needs some inspiration initially, so attempting to duplicate an existing closed source application on the marketplace may not be a too bad starting point, as long as you do give credit to the original application designers too. I am lucky enough to have an idea that seems to be reasonably unique (from my research) in the Android Market Place. While I do not wish to divulge my idea (some people tend to steal ideas), I will document my progress and any things that I learn along the way in a similar fashion as this blog did. So check back often.

“I cannot give you the idea, but I can give you the tools to achieve it”

Sunday 6 February 2011

Part 2: That Sample Application

Index:
1. First dabble with Google Android
2. That Sample
3. TipCalc Sample

Summarising my previous post, I decided to try out this sample as an introduction to the Android SDK. Let me first give some credit to this sample blog, it gave some very good pointers and I greatly appreciate the help it provided. My blog is not meant to be taking any glory from anyone else, but instead document my journey so that others can learn alongside me. So, see this entry into my blog as "additional help" to the sample blog. Hopefully once I get the hang of the Android SDK, I will be able to contribute my own original ideas.

I started by downloading the Android SDK, Apache Ant, Java JDK and DroidDraw. So far so good. It then became clear that things has changed since sample blog was posted. A few deviations I had to take from the scripted sample:

1) I had some trouble running the "emulator.exe" application, but after some playing around, I found that the emulator can be started from within the SDK Manager (c:\tools\android\). From there, you can select the top most menu item (Virtual Devices) and create a new AVD (Android Virtual Device) using the version of the SDK you specify. I used 2.1 because my version of Android on my Galaxy S was still running Eclair. Once created, simply select the new AVD and click Start.

2) The next place I hit a wall was running "activitycreator.bat", it simply did not exist in the directory specified in the blog. Reading through the comments, I found that activitycreator.bat has been replaced by android.bat. So, as stated in the comments, I ran "android create project --activity tipcalc --target 2 --path ./tipcalc --package com.andriod.tipcalc". One thing to note here is the value of "target", it is 1 in my case, but it refers to the ordinal that your version of the AVD is pointing to (2,1 in my case). This can be found by typing "android list" in a command prompt.

3) Another issue was with the path of java (aka JAVA_HOME). The blog says to put java in c:\tools\java, problem is that Java automatically installs itself in c:\program files\java. Because of this, I didn't want to move the Java directory anywhere else, in case another application relies on it being in Program files. This meant that I simply had to change my environment variable for JAVA_HOME to "c:\ Program Filed\Java\jdk1.6.0_23", which I did. But for some reason I kept on getting this error, when running ant. Turns out that the issue wasn't the path, but the fact that the command prompt does not refresh it's environment variables automatically, so simply opening up another cmd refreshed the environment variables for that cmd session. The simplest way to check this is to simply type "set" in the command prompt and see what the value for JAVA_HOME is. There is probably a way to force cmd to refresh it's environment variables without restarting cmd, but since this was not a too important issue, I am not going to try and figure that out. I am trying to write an Android app, after all.

4) After all that, ant didn't really compile the project as expected (I am starting to think this this sample is not the best place to start). So, instead of just running "ant", I ran "ant compile". The ant compiler seemed to compile the project, even though it gave some compile errors. I am going to assume that these errors were actually warnings, but may revise that opinion soon. (Update: looks there are easier ways to do this, see my next blog for more details)

5) Next issue was that the location of adb has changed from \android\tools to \android\platform-tools. This is specified in a text document called "adb_has_moved.txt" in the \android\tools directory. I followed the instructions in that text file and added "c:\tools\android\platform-tools" to my PATH variable so that it is easier to execute it in the future. This once again required a cmd restart :(. But after a cmd restart, I was able to run "adb install \bin\tipcalc-debug.apk". This installed the application on the emulator. (Update: looks like there are easier ways to do this, see my next blog for more details)

So, finally I have my Hello World application on the emulator. Now to run it. So I open the menu on the emulator and Eureka, the application is on the device. Running it returns the default "Hello World" application. Mission accomplished!!

So, in conclusion, a lot seems to have changed in the SDK since this sample blog was written. the blog does not have a created date, but the comments on the blog indicates it was written in late 2008. Maybe in hindsight I should have checked how "out of date" the blog was before I started this blog. But at least I learned a little bit more than I would have if the blog was up to date.

In my next post I will focus and break down the actual code used in the TipCalc sample

Part 1: First dabble with Google Android

Index:
1. First dabble with Google Android
2. That Sample
3. TipCalc Sample

After avoiding the subject for a long time, I finally decided to upgrade my smart phone from a Palm Treo running Windows Mobile 6 to a newer model. Since I am generally not a fan of Apple's lack of openness, this left me with only one viable alternative, our friend Mr. Google Android.

I spent some time doing some research and decided on the Samsung Galaxy S (also known as Captivate and GT-I9000). Now normally when one wants to buy a new toy, you build it up in your mind quite a bit. So when you end up getting the new toy, it never really lives up to expectation. Sometimes it bombs out completely, other times it gets close enough to your expectation to be satisfied. When it comes to the Galaxy S, the entire thing blew away all my expectations. It was so awesome that I cannot stop talking about it.

So what makes it so awesome. That's a difficult question because I have not played with other Android phones before (I have played with iPhones and iPads though). I think it is a bit of everything, the hardware is substantial (although the battery life suffers from the standard smart phone curse), Android is very useful and the Android Market Place has so many apps that it is impossible to make a top 10 list.

I must say that the only issue I have is that the Android Market itself is a little hard to browse because of the broad application categorization. That said, if you know what you're searching for, everything is at your fingertips.

Now, with the preamble out of the way, I decided to try my hand at developing an Android Application. While I have several years development experience, most of that has been in Microsoft technologies, so I knew I had a big learning curve ahead of me. The first thing I had to do was read the Android documentation. There is a lot to learn, and simply reading the documentation without really having a baseline was never going to go down well. So I decided to find a sample application online and see if I can recreate it. I stumbles onto this blog and decided that this is a good starting point to give me an introduction to the Android SDK, Eclipse and any other Android tools.

In my next blog post, I will post my experience from the sample application above.