Wednesday, 28 September 2011

Android for the Java Developer - part 2

In part 1, there was a brief introduction to developing on Android from a Java programmer's perspective, with some of the similarities and differences highlighted.

The purpose of this article is look at some of these differences in more detail. For a pre-existing Java app, these are effectively the parts of an app that would require Android-specific development rather than simply re-using Java code. As a Java developer myself, they are also the differences I first noticed when I started to develop with Android.

When comparing the Java and Android development process, it's worth remembering that the two languages are there to address requirements. A client-side Java app would usually have been written for a desktop computer with a large screen, mouse and keyboard. In contrast, the Android app is likely to be running on a smaller device with touch screen and (possibly) no keyboard. In addition, the Android device may have other features you may want to make use of such as the GPS for location information, or the accelerometer.
That said, now let us look at some common tasks and consider how to approach them in Android...

User Interface Layouts

Most commonly, writing Java user interfaces meant using the java.awt or javax.swing packages. Due to a lack of good-quality UI building tools, this may have meant some painful manual coding. Anyone who has wrestled with the finer points of GridBagLayouts and the like knows what I mean. The good news is that Android makes UI design a lot easier by defining an XML-based layout language. Here is a fairly readable example of an XML fragment that produces a component with two buttons, labelled "Start" and "Exit":
<LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp" android:orientation="vertical" <Button android:id="@+id/button_start" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Start" android:textSize="16dp" android:drawableLeft="@drawable/icon_start"/> <Button android:id="@+id/button_exit" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Exit" android:textSize="16dp" android:drawableLeft="@drawable/icon_exit"/> </LinearLayout>
Essentially your Android app should contain an XML layout file like this for each screen, which simply needs to be saved in the correct location (PROJECT_DIR/res/layout) in your project.

Handling Events

In Java, UI components and controls (such as buttons, menus, checkboxes, etc) have the ability for listeners to be assigned. The listener responds to any events from the component, such as a button press in this example:
Button startButton = new Button("Start"); startButton.addActionListener(new MyActionListener()); public class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent evt) { //the button was pressed! } }
In Android, the model is almost exactly the same. Assuming the button in question has been defined in the XML layout file (see above), we can access the button in code and define a listener as follows:
Button startButton = findViewById(R.id.button_start); startButton.setOnClickListener(new MyOnClickListener()); public class MyOnClickListener implements OnClickListener { public void onClick(View view) { //the button was pressed! } }

Loading Graphics

Most applications will need to load image resources. In java, depending on how your project is structured, you may have something similar to this:
public class ImageHandler { private Image titleImage; public void loadImages() { URL url = ImageHandler.class.getResource("title.png"); if (url != null){ titleImage = Toolkit.getDefaultToolkit().getImage(url); } ... } }
In Android, some of the work is done for you. The image file simply needs to be dropped into a standard location in your project (PROJECT_DIR/res/drawable). The equivalent code would be:
public class ImageHandler { private Drawable titleImage; public void loadImages() { titleImage = resources.getDrawable(R.drawable.title); } ... }
The "R" class in Android is auto-generated by the build process. All your resources (images, sounds, layouts) can be accessed via this class.

On-screen Rendering

Sometimes you may need to draw shapes or images directly on screen using a Graphics context. This is typically the case with simple games. In a Java Applet/Application, you can use the Graphics or Graphics2D class do this:
public void paint(Graphics g) { //change the colour g.setColor(Color.BLUE); //draw some text g.drawString("Hello world", x1, y1); //draw a rectangle g.drawRect(x1, y1, wd, ht); //draw an image g.drawImage(titleImage, x1, y1, wd, ht, null); }
In Android, the approach is similar. There is a SurfaceHolder interface from which you can get a Canvas object to use for your drawing:
public void paint(Canvas canvas) { Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); //change the colour paint.setColor(Color.BLUE); //draw some text canvas.drawText("Hello world", x1, y1, paint); //draw a rectangle canvas.drawRect(x1, y1, x2, y2, paint); //draw an image titleImage.setBounds(x1, y1, x2, y2); titleImage.draw(canvas); }
Important differences to note: (1) In Android, it is necessary to create a Paint object - this will control details such as the colour, line thickness, etc of drawn objects. (2) In Android, methods such as drawRect use the coordinates of the rectangle's vertices (x1,y1) -> (x2,y2), rather than the width and height arguments as used by Java's drawRect.

Summary

We looked at some factors a developer needs to be aware of when developing on both Java and Android platforms, or when learning Android from a background in Java.

There are lots of other differences between the languages of course, but hopefully these represent a good starting point. Let me know if you think there should be more articles along these lines. The next article will be about using AdMob to generate income from in-app advertising.

Wednesday, 21 September 2011

Android for the Java Developer - part 1

In this article, we will look at beginning Android development from a Java programmer's perspective. We will take a look at the similarities and differences between Java and Android, and consider how these may affect how best to develop an Android app. The information may assist if you are, for example:
  • Converting an existing Java program to Android.
  • Developing an application for both Java and Android.
  • Have some experience with Java and want to learn Android.

Android can be thought of as a direct descendant of Java. Not only do the languages share are large common core, but also many existing Java libraries can be used in Android apps directly and without modification or recompilation. This makes Android a relatively easy step for anyone who has a Java background.

Let's take a look at some of the well-known package names from the Java SDK. Those on the left are also included in Android. Those on the right are in Java only.
Packages in Java AND Android ¹ Packages in Java but NOT Android
  • java.beans
  • java.io
  • java.lang
  • java.math
  • java.net
  • java.nio
  • java.security
  • java.sql
  • java.text
  • java.util
  • javax.crypto
  • javax.net
  • javax.sql
  • javax.xml
  • java.applet
  • java.awt
  • java.rmi
  • javax.sound
  • javax.swing
  • javax.tools
¹ Top level packages only, not an exhaustive list.

It's clear that a very large chunk of the JDK is available to the Android developer. In addition, because Java libraries can incorporated into an Android app, it means any existing Java library can be used as long as it only needs packages from the left-hand column.

Turning now to the right-hand column, arguably the most significant "missing" packages are the ones related to user interface building, java.awt and javax.swing. This is because Android has its own system for building UI elements - more on this in another article coming soon.

So what to conclude from this, and how should it affect the design of an Android app we might want to build? Good application design should separate the core program logic from the user interface. If this principle is used, it will also make life easier should you want work with both Java and Android. The program logic parts of the app are typically going to use packages common to both languages, and hence can be easily reused.

A pure Java user interface cannot be reused however, and so an Android-specific version will need to be built. We will look at aspect more in the next article (coming soon).

For those developing an application for both Java and Android, or wanting to migrate an existing Java application to Android, here is a simplified diagram of how an app might be structured.


In the next article, we will explore in more detail the differences between Java and Android, and how we might navigate these to build our Android app.

Friday, 9 September 2011

What's this all about?

I am long-time programmer who started experimenting with the Java language in the late 1990s when the latest JDK version was only 1.1. In those days I created a number of simple browser-based applet games which I then put on my website, http://spwebgames.com/.

After that, my main focus shifted to what became the mainstay of Java development, server-side web applications. However, In late 2009, with Android set to become the next big hit in the mobile device world, I decided to dust off these applets with a view further developing and converting them to Android.

I now have over 10 apps released on Android Market with the degree of success varying markedly (Downloads ranging from around a thousand to several hundred thousands). I decided it was time write some notes on my experiences, and in particular, on these topics:

- The current state and future of Android development
- Using in-app advertising services to generate income
- Converting Java applications/applets to Android
- Programming for the web
- Anything else that comes to mind