Sunday, August 19, 2012

Java RMI Tutorial

Introduction

This is a brief introduction to Java Remote Method Invocation (RMI). Java RMI is a mechanism that allows one to invoke a method on an object that exists in another address space. The other address space could be on the same machine or a different one. The RMI mechanism is basically an object-oriented RPC mechanism. CORBA is another object-oriented RPC mechanism. CORBA differs from Java RMI in a number of ways:
  1. CORBA is a language-independent standard.
  2. CORBA includes many other mechanisms in its standard (such as a standard for TP monitors) none of which are part of Java RMI.
  3. There is also no notion of an "object request broker" in Java RMI.
Java RMI has recently been evolving toward becoming more compatible with CORBA. In particular, there is now a form of RMI called RMI/IIOP ("RMI over IIOP") that uses the Internet Inter-ORB Protocol (IIOP) of CORBA as the underlying protocol for RMI communication.
This tutorial attempts to show the essence of RMI, without discussing any extraneous features. Sun has provided a Guide to RMI, but it includes a lot of material that is not relevant to RMI itself. For example, it discusses how to incorporate RMI into an Applet, how to use packages and how to place compiled classes in a different directory than the source code. All of these are interesting in themselves, but they have nothing at all to do with RMI. As a result, Sun's guide is unnecessarily confusing. Moreover, Sun's guide and examples omit a number of details that are important for RMI.
There are three processes that participate in supporting remote method invocation.
  1. The Client is the process that is invoking a method on a remote object.
  2. The Server is the process that owns the remote object. The remote object is an ordinary object in the address space of the server process.
  3. The Object Registry is a name server that relates objects with names. Objects are registered with the Object Registry. Once an object has been registered, one can use the Object Registry to obtain access to a remote object using the name of the object.
In this tutorial, we will give an example of a Client and a Server that solve the classical "Hello, world!" problem. You should try extracting the code that is presented and running it on your own computer.
There are two kinds of classes that can be used in Java RMI.
  1. A Remote class is one whose instances can be used remotely. An object of such a class can be referenced in two different ways:
    1. Within the address space where the object was constructed, the object is an ordinary object which can be used like any other object.
    2. Within other address spaces, the object can be referenced using an object handle. While there are limitations on how one can use an object handle compared to an object, for the most part one can use object handles in the same way as an ordinary object.
    For simplicity, an instance of a Remote class will be called a remote object.
  2. A Serializable class is one whose instances can be copied from one address space to another. An instance of a Serializable class will be called a serializable object. In other words, a serializable object is one that can be marshaled. Note that this concept has no connection to the concept of serializability in database management systems. If a serializable object is passed as a parameter (or return value) of a remote method invocation, then the value of the object will be copied from one address space to the other. By contrast if a remote object is passed as a parameter (or return value), then the object handle will be copied from one address space to the other.
One might naturally wonder what would happen if a class were both Remote and Serializable. While this might be possible in theory, it is a poor design to mix these two notions as it makes the design difficult to understand.

Serializable Classes

We now consider how to design Remote and Serializable classes. The easier of the two is a Serializable class. A class is Serializable if it implements the java.io.Serializable interface. Subclasses of a Serializable class are also Serializable. Many of the standard classes are Serializable, so a subclass of one of these is automatically also Serializable. Normally, any data within a Serializable class should also be Serializable. Although there are ways to include non-serializable objects within a serializable objects, it is awkward to do so. See the documentation of java.io.Serializable for more information about this.
Using a serializable object in a remote method invocation is straightforward. One simply passes the object using a parameter or as the return value. The type of the parameter or return value is the Serializable class. Note that both the Client and Server programs must have access to the definition of any Serializable class that is being used. If the Client and Server programs are on different machines, then class definitions of Serializable classes may have to be downloaded from one machine to the other. Such a download could violate system security. This problem is discussed in the Security section.
The only Serializable class that will be used in the "Hello, world!" example is the String class, so no problems with security arise.

Remote Classes and Interfaces

Next consider how to define a Remote class. This is more difficult than defining a Serializable class. A Remote class has two parts: the interface and the class itself. The Remote interface must have the following properties:
  1. The interface must be public.
  2. The interface must extend the interface java.rmi.Remote.
  3. Every method in the interface must declare that it throws java.rmi.RemoteException. Other exceptions may also be thrown.
The Remote class itself has the following properties:
  1. It must implement a Remote interface.
  2. It should extend the java.rmi.server.UnicastRemoteObject class. Objects of such a class exist in the address space of the server and can be invoked remotely. While there are other ways to define a Remote class, this is the simplest way to ensure that objects of a class can be used as remote objects. See the documentation of the java.rmi.server package for more information.
  3. It can have methods that are not in its Remote interface. These can only be invoked locally.
Unlike the case of a Serializable class, it is not necessary for both the Client and the Server to have access to the definition of the Remote class. The Server requires the definition of both the Remote class and the Remote interface, but the Client only uses the Remote interface. Roughly speaking, the Remote interface represents the type of an object handle, while the Remote class represents the type of an object. If a remote object is being used remotely, its type must be declared to be the type of the Remote interface, not the type of the Remote class. In the example program, we need a Remote class and its corresponding Remote interface. We call these Hello and HelloInterface, respectively. Here is the file HelloInterface.java:
import java.rmi.*;
/**
 * Remote Interface for the "Hello, world!" example.
 */
public interface HelloInterface extends Remote {
  /**
   * Remotely invocable method.
   * @return the message of the remote object, such as "Hello, world!".
   * @exception RemoteException if the remote invocation fails.
   */
  public String say() throws RemoteException;
}
Here is the file Hello.java:
import java.rmi.*;
import java.rmi.server.*;
/**
 * Remote Class for the "Hello, world!" example.
 */
public class Hello extends UnicastRemoteObject implements HelloInterface {
  private String message;
  /**
   * Construct a remote object
   * @param msg the message of the remote object, such as "Hello, world!".
   * @exception RemoteException if the object handle cannot be constructed.
   */
  public Hello (String msg) throws RemoteException {
    message = msg;
  }
  /**
   * Implementation of the remotely invocable method.
   * @return the message of the remote object, such as "Hello, world!".
   * @exception RemoteException if the remote invocation fails.
   */
  public String say() throws RemoteException {
    return message;
  }
}
All of the Remote interfaces and classes should be compiled using javac. Once this has been completed, the stubs and skeletons for the Remote interfaces should be compiled by using the rmic stub compiler. The stub and skeleton of the example Remote interface are compiled with the command:
  rmic Hello
The only problem one might encounter with this command is that rmic might not be able to find the files Hello.class and HelloInterface.class even though they are in the same directory where rmic is being executed. If this happens to you, then try setting the CLASSPATH environment variable to the current directory, as in the following command:
  setenv CLASSPATH .
If your CLASSPATH variable already has some directories in it, then you might want to add the current directory to the others.

Programming a Client

Having described how to define Remote and Serializable classes, we now discuss how to program the Client and Server. The Client itself is just a Java program. It need not be part of a Remote or Serializable class, although it will use Remote and Serializable classes.
A remote method invocation can return a remote object as its return value, but one must have a remote object in order to perform a remote method invocation. So to obtain a remote object one must already have one. Accordingly, there must be a separate mechanism for obtaining the first remote object. The Object Registry fulfills this requirement. It allows one to obtain a remote object using only the name of the remote object.
The name of a remote object includes the following information:
  1. The Internet name (or address) of the machine that is running the Object Registry with which the remote object is being registered. If the Object Registry is running on the same machine as the one that is making the request, then the name of the machine can be omitted.
  2. The port to which the Object Registry is listening. If the Object Registry is listening to the default port, 1099, then this does not have to be included in the name.
  3. The local name of the remote object within the Object Registry.
Here is the example Client program:
  /**
   * Client program for the "Hello, world!" example.
   * @param argv The command line arguments which are ignored.
   */
  public static void main (String[] argv) {
    try {
      HelloInterface hello = 
        (HelloInterface) Naming.lookup ("//ortles.ccs.neu.edu/Hello");
      System.out.println (hello.say());
    } catch (Exception e) {
      System.out.println ("HelloClient exception: " + e);
    }
  }
The Naming.lookup method obtains an object handle from the Object Registry running on ortles.ccs.neu.edu and listening to the default port. Note that the result of Naming.lookup must be cast to the type of the Remote interface.
The remote method invocation in the example Client is hello.say(). It returns a String which is then printed. A remote method invocation can return a String object because String is a Serializable class.
The code for the Client can be placed in any convenient class. In the example Client, it was placed in a class HelloClient that contains only the program above.

Programming a Server

The Server itself is just a Java program. It need not be a Remote or Serializable class, although it will use them. The Server does have some responsibilities:
  1. If class definitions for Serializable classes need to be downloaded from another machine, then the security policy of your program must be modified. Java provides a security manager class called RMISecurityManager for this purpose. The RMISecurityManager defines a security policy that allows the downloading of Serializable classes from another machine. The "Hello, World!" example does not need such downloads, since the only Serializable class it uses is String. As a result it isn't necessary to modify the security policy for the example program. If your program defines Serializable classes that need to be downloaded to another machine, then insert the statement System.setSecurityManager (new RMISecurityManager()); as the first statement in the main program below. If this does not work for your program, then you should consult the Security section below.
  2. At least one remote object must be registered with the Object Registry. The statement for this is: Naming.rebind (objectName, object); where object is the remote object being registered, and objectName is the String that names the remote object.
Here is the example Server:
  /**
   * Server program for the "Hello, world!" example.
   * @param argv The command line arguments which are ignored.
   */
  public static void main (String[] argv) {
    try {
      Naming.rebind ("Hello", new Hello ("Hello, world!"));
      System.out.println ("Hello Server is ready.");
    } catch (Exception e) {
      System.out.println ("Hello Server failed: " + e);
    }
  }
The rmiregistry Object Registry only accepts requests to bind and unbind objects running on the same machine, so it is never necessary to specify the name of the machine when one is registering an object. The code for the Server can be placed in any convenient class. In the example Server, it was placed in a class HelloServer that contains only the program above.

Starting the Server

Before starting the Server, one should first start the Object Registry, and leave it running in the background. One performs this by using the command:
  rmiregistry &
It takes a second or so for the Object Registry to start running and to start listening on its socket. If one is using a script, then one should program a pause after starting the Object Registry. If one is typing at the command line, it is unlikely that one could type fast enough to get ahead of the Object Registry. The Server should then be started; and, like the Object Registry, left running in the background. The example Server is started using the command:
  java HelloServer &
The Server will take a few seconds to start running, and to construct and register remote objects. So one should wait a few seconds before running any Clients. Printing a suitable message, as in the example Server, is helpful for determining when the Server is ready.

Running a Client

Th Client is run like any other java program. The example Client is executed using:
  java HelloClient

Security

One of the most common problems one encounters with RMI is a failure due to security constraints. This section gives a very brief introduction to the Java security model as it relates to RMI. For a more complete treatment, one should read the documentation for the Java SecurityManager and Policy classes and their related classes. Note that this section assumes that one is using Java 1.2 or later. Some of the statements are not true for earlier versions.
A Java program may specify a security manager that determines its security policy. A program will not have any security manager unless one is specified. One sets the security policy by constructing a SecurityManager object and calling the setSecurityManager method of the System class. Certain operations require that there be a security manager. For example, RMI will download a Serializable class from another machine only if there is a security manager and the security manager permits the downloading of the class from that machine. The RMISecurityManager class defines an example of a security manager that normally permits such downloads.
However, many Java installations have instituted security policies that are more restrictive than the default. There are good reasons for instituting such policies, and one should not override them carelessly. The rest of this section discusses some ways that can be used for overriding security policies that prevent RMI from functioning properly.
The SecurityManager class has a large number of methods whose name begins with check. For example, checkConnect (String host, int port). If a check method returns, then the permission was granted. For example, if a call to checkConnect returns normally, then the current security policy allows the program to establish a socket connection to the server socket at the specified host and port. If the current security policy does not allow one to connect to this host and port, then the call throws an exception. This usually causes your program to terminate with a message such as:
  java.security.AccessControlException: access denied
  (java.net.SocketPermission 127.0.0.1:1099 connect,resolve)
The message above would occur when an RMI server or client was not allowed to connect to the RMI registry running on the same machine as the server or client. As discussed above, one sets the security policy by passing an object of type SecurityManager to the setSecurityManager method of the System class. There are several ways to modify the security policy of a program. The simplest technique is to define a subclass of SecurityManager and to call System.setSecurityManager on an object of this subclass. In the definition of this subclass, you should override those check methods for which you want a different policy. For example, if you find that your "Hello, World!" program refuses to connect to the registry, then you should override the checkConnect methods. There are two checkConnect methods. The first was discussed above, and the second checkConnect method has a third parameter that specifies the security context of the request.
The following code illustrates how to do this:
  System.setSecurityManager (new RMISecurityManager() {
    public void checkConnect (String host, int port) {}
    public void checkConnect (String host, int port, Object context) {}
  });
The code above uses an anonymous inner class. Such a class is convenient when the class will only be used to construct an object in one place, as in this example. Of course, one could also define the subclass of RMISecurityManager in the usual way.
Defining and installing a security manager was the original technique for specifying a security policy in Java. Unfortunately, it is very difficult to design such a class so that it does not leave any security holes. For this reason, a new technique was introduced in Java 1.2, which is backward compatible with the old technique. In the default security manager, all check methods (except checkPermission) are implemented by calling the checkPermission method. The type of permission being checked is specified by the parameter of type Permission passed to the checkPermission method. For example, the checkConnect method calls checkPermission with a SocketPermission object. The default implementation of checkPermission is to call the checkPermission method of the AccessController class. This method checks whether the specified permission is implied by a list of granted permissions. The Permissions class is used for maintaining lists of granted permissions and for checking whether a particular permission has been granted.
This is the mechanism whereby the security manager checks permissions, but it does not explain how one specifies or changes the security policy. For this purpose there is yet another class, named Policy. Like SecurityManager, each program has a current security policy that can be obtained by calling Policy.getPolicy(), and one can set the current security policy using Policy.setPolicy, if one has permission to do so. The security policy is typically specified by a policy configuration file (or "policy file" for short) which is read when the program starts and any time that a request is made to refresh the security policy. The policy file defines the permissions contained in a Policy object. It is not inaccurate to think of the policy file a kind of serialization of a Policy object (except that a policy file is intended to be readable by humans as well as by machines). As an example, the following will grant all permissions of any kind to code residing in the RMI directory on the C: drive:
  grant codeBase "file:C:/RMI/-" {
    permission java.security.AllPermission;
  };
The default security manager uses a policy that is defined in a collection of policy files. For the locations of these files see the documentation of the policytool program. If one wishes to grant additional permissions, then one can specify them in a policy file and then request that they be loaded using options such as the following:
java -Djava.security.manager -Djava.security.policy=policy-file MyClass
Both of the "-D" options specify system properties. The first system property has the same effect as executing the following statement as the first statement in your program:
  System.setSecurityManager (new SecurityManager());
The second system property above causes the specified policy-file (which is specified with a URL) to be added to the other policy files when defining the entire security policy. The policytool can be used to construct the policy file, but one can also use any text editor. As if this wasn't already complicated enough, there is yet another way to deal with the problem of downloading Serializable classes. The command-line option -Djava.rmi.server.codebase=code-base specifies a location from which Serializable classes may be downloaded. Of course, your security manager must recognize this system property, and not all of them will do so. Furthermore, as mentioned earlier, this is only necessary if you actually need to download Serializable classes.


Thursday, July 7, 2011

Comparison of the Java and .NET platforms

Traditional computer applications

Desktop applications

 

Although Java's AWT (Abstract Windowing Toolkit) and Swing libraries are not shy of features, Java has struggled to establish a foothold in the desktop market. Sun Microsystems has also been slow, in the eyes of some, to promote Java to developers and end users alike in a way which makes it an appealing choice for desktop software. Even technologies such as Java Web Start, which have few parallels within rival languages and platforms, have barely been promoted. 

The release of Java version 6.0 on December 11, 2006, saw a renewed focus on the desktop market with an extensive set of new tools for closer integration with the desktop. At the 2007 JavaOne conference Sun made further desktop related announcements, including a new language aimed at taking on Adobe Flash (JavaFX), a new lightweight way of downloading the JRE which sees the initial footprint reduced to under 2Mb, and a renewed focus on multimedia libraries.

An alternative to AWT and Swing is the Standard Widget Toolkit (SWT), which was originally developed by IBM and now maintained by the Eclipse Foundation. It attempts to achieve improved performance and visualization of Java desktop applications by relying on underlying native libraries where possible.

On Windows, Microsoft's .NET is popular desktop development providing both Windows Forms (a lightweight wrapper around the Win32 API), Windows Presentation Foundation, and Silverlight. With the integration of .NET into the Windows platform, .NET apps are first class citizens in the Windows environment with tighter OS integration and native look and feel compared to Java's Swing. Outside of Windows, Silverlight is portable to the Mac OSX desktop. Mono is also becoming more common in open source and free software systems due to its inclusion on many Linux desktop environments.

Server applications

 

This is probably the arena in which the two platforms are closest to being considered rivals. Java, through its Java EE (a.k.a. Java Platform Enterprise Edition) platform, and .NET through ASP.NET, compete to create web-based dynamic content and applications.

Both platforms are well used and supported in this market, with a bevy of tools and supporting products available for Java EE and .NET. High-end, large-scale, heavy duty solutions tend to opt for Java EE due to higher stability, scalability, and greater availability of senior developers. For example, for Java: Oracle included direct support for Java into its database, while Google has used Java to power tools like Gmail.

Some of Sun's current Java-related license agreements for Java EE define aspects of the Java platform as a trade secret, and prohibit the end user from contributing to a third-party Java environment. Specifically, at least one current license for a Sun Java EE development package contains the following terms:  

"You may make a single archival copy of Software, but otherwise may not copy, modify, or distribute Software." — "Unless enforcement is prohibited by applicable law, you may not decompile, or reverse engineer Software." — "You may not publish or provide the results of any benchmark or comparison tests run on Software to any third party without the prior written consent of Sun." — "Software is confidential and copyrighted." 

However, while Sun's software is subject to the above license terms, Sun's Java EE API reference has been implemented under an open source license by the JBoss and JOnAS projects.Microsoft's implementation of ASP.NET is not part of the standardized CLI, and while Microsoft's runtime environment and development tools are not subject to comparable secrecy agreements to Java EE, the official Microsoft tools are not open source or free software, and require Windows servers. However, a cross-platform free software ASP.NET 2.0 implementation is part of the Mono project (minus webparts and Web Services Enhancements).

Java and Android

Create an AVD

In this tutorial, you will run your application in the Android Emulator. Before you can launch the emulator, you must create an Android Virtual Device (AVD). An AVD defines the system image and device settings used by the emulator.
To create an AVD:
  1. In Eclipse, choose Window > Android SDK and AVD Manager.
  2. Select Virtual Devices in the left panel.
  3. Click New.
  4. The Create New AVD dialog appears.
  5. Type the name of the AVD, such as "my_avd".
  6. Choose a target. The target is the platform (that is, the version of the Android SDK, such as 2.1) you want to run on the emulator.
  7. You can ignore the rest of the fields for now.
  8. Click Create AVD.

Create a New Android Project

After you've created an AVD, the next step is to start a new Android project in Eclipse.
  1. From Eclipse, select File > New > Project. If the ADT Plugin for Eclipse has been successfully installed, the resulting dialog should have a folder labeled "Android" which should contain "Android Project". (After you create one or more Android projects, an entry for "Android XML File" will also be available.)
  2. Select "Android Project" and click Next.
  3. Fill in the project details with the following values:
    • Project name: HelloAndroid
    • Application name: Hello, Android
    • Package name: com.example.helloandroid (or your own private namespace)
    • Create Activity: HelloAndroid
    Click Finish.
    Here is a description of each field:
    Project Name
    This is the Eclipse Project name — the name of the directory that will contain the project files.
    Application Name
    This is the human-readable title for your application — the name that will appear on the Android device.
    Package Name
    This is the package namespace (following the same rules as for packages in the Java programming language) that you want all your source code to reside under. This also sets the package name under which the stub Activity will be generated. Your package name must be unique across all packages installed on the Android system; for this reason, it's important to use a standard domain-style package for your applications. The example above uses the "com.example" namespace, which is a namespace reserved for example documentation — when you develop your own applications, you should use a namespace that's appropriate to your organization or entity.
    Create Activity
    This is the name for the class stub that will be generated by the plugin. This will be a subclass of Android's Activity class. An Activity is simply a class that can run and do work. It can create a UI if it chooses, but it doesn't need to. As the checkbox suggests, this is optional, but an Activity is almost always used as the basis for an application.
    Min SDK Version
    This value specifies the minimum API Level required by your application. For more information, see Android API Levels.
    Other fields: The checkbox for "Use default location" allows you to change the location on disk where the project's files will be generated and stored. "Build Target" is the platform target that your application will be compiled against (this should be selected automatically, based on your Min SDK Version).
    Notice that the "Build Target" you've selected uses the Android 1.1 platform. This means that your application will be compiled against the Android 1.1 platform library. If you recall, the AVD created above runs on the Android 1.5 platform. These don't have to match; Android applications are forward-compatible, so an application built against the 1.1 platform library will run normally on the 1.5 platform. The reverse is not true.

Your Android project is now ready. It should be visible in the Package Explorer on the left. Open the HelloAndroid.java file, located inside HelloAndroid > src > com.example.helloandroid). It should look like this:
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
Notice that the class is based on the Activity class. An Activity is a single application entity that is used to perform actions. An application may have many separate activities, but the user interacts with them one at a time. The onCreate() method will be called by the Android system when your Activity starts — it is where you should perform all initialization and UI setup. An activity is not required to have a user interface, but usually will.
Now let's modify some code!

Construct the UI

Take a look at the revised code below and then make the same changes to your HelloAndroid class. The bold items are lines that have been added.
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       TextView tv = new TextView(this);
       tv.setText("Hello, Android");
       setContentView(tv);
   }
}
Tip: An easy way to add import packages to your project is to press Ctrl-Shift-O (Cmd-Shift-O, on Mac). This is an Eclipse shortcut that identifies missing packages based on your code and adds them for you.
An Android user interface is composed of hierarchies of objects called Views. A View is a drawable object used as an element in your UI layout, such as a button, image, or (in this case) a text label. Each of these objects is a subclass of the View class and the subclass that handles text is TextView.
In this change, you create a TextView with the class constructor, which accepts an Android Context instance as its parameter. A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. The Activity class inherits from Context, and because your HelloAndroid class is a subclass of Activity, it is also a Context. So, you can pass this as your Context reference to the TextView.
Next, you define the text content with setText().
Finally, you pass the TextView to setContentView() in order to display it as the content for the Activity UI. If your Activity doesn't call this method, then no UI is present and the system will display a blank screen.
There it is — "Hello, World" in Android! The next step, of course, is to see it running.

Run the Application

The Eclipse plugin makes it easy to run your applications:
  1. Select Run > Run.
  2. Select "Android Application".
The Eclipse plugin automatically creates a new run configuration for your project and then launches the Android Emulator. Depending on your environment, the Android emulator might take several minutes to boot fully, so please be patient. When the emulator is booted, the Eclipse plugin installs your application and launches the default Activity. You should now see something like this:
The "Hello, Android" you see in the grey bar is actually the application title. The Eclipse plugin creates this automatically (the string is defined in the res/values/strings.xml file and referenced by your AndroidManifest.xml file). The text below the title is the actual text that you have created in the TextView object.
That concludes the basic "Hello World" tutorial, but you should continue reading for some more valuable information about developing Android applications.

Upgrade the UI to an XML Layout

The "Hello, World" example you just completed uses what is called a "programmatic" UI layout. This means that you constructed and built your application's UI directly in source code. If you've done much UI programming, you're probably familiar with how brittle that approach can sometimes be: small changes in layout can result in big source-code headaches. It's also easy to forget to properly connect Views together, which can result in errors in your layout and wasted time debugging your code.
That's why Android provides an alternate UI construction model: XML-based layout files. The easiest way to explain this concept is to show an example. Here's an XML layout file that is identical in behavior to the programmatically-constructed example:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/textview"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:text="@string/hello"/>
The general structure of an Android XML layout file is simple: it's a tree of XML elements, wherein each node is the name of a View class (this example, however, is just one View element). You can use the name of any class that extends View as an element in your XML layouts, including custom View classes you define in your own code. This structure makes it easy to quickly build up UIs, using a more simple structure and syntax than you would use in a programmatic layout. This model is inspired by the web development model, wherein you can separate the presentation of your application (its UI) from the application logic used to fetch and fill in data.
In the above XML example, there's just one View element: the TextView, which has five XML attributes. Here's a summary of what they mean:
Attribute Meaning
xmlns:android This is an XML namespace declaration that tells the Android tools that you are going to refer to common attributes defined in the Android namespace. The outermost tag in every Android layout file must have this attribute.
android:id This attribute assigns a unique identifier to the TextView element. You can use the assigned ID to reference this View from your source code or from other XML resource declarations.
android:layout_width This attribute defines how much of the available width on the screen this View should consume. In this case, it's the only View so you want it to take up the entire screen, which is what a value of "fill_parent" means.
android:layout_height This is just like android:layout_width, except that it refers to available screen height.
android:text This sets the text that the TextView should display. In this example, you use a string resource instead of a hard-coded string value. The hello string is defined in the res/values/strings.xml file. This is the recommended practice for inserting strings to your application, because it makes the localization of your application to other languages graceful, without need to hard-code changes to the layout file. For more information, see Resources and Internationalization.
These XML layout files belong in the res/layout/ directory of your project. The "res" is short for "resources" and the directory contains all the non-code assets that your application requires. In addition to layout files, resources also include assets such as images, sounds, and localized strings.
The Eclipse plugin automatically creates one of these layout files for you: main.xml. In the "Hello World" application you just completed, this file was ignored and you created a layout programmatically. This was meant to teach you more about the Android framework, but you should almost always define your layout in an XML file instead of in your code. The following procedures will instruct you how to change your existing application to use an XML layout.
  1. In the Eclipse Package Explorer, expand the /res/layout/ folder and open main.xml (once opened, you might need to click the "main.xml" tab at the bottom of the window to see the XML source). Replace the contents with the following XML:
    <?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/textview"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:text="@string/hello"/>
    Save the file.
  2. Inside the res/values/ folder, open strings.xml. This is where you should save all default text strings for your user interface. If you're using Eclipse, then ADT will have started you with two strings, hello and app_name. Revise hello to something else. Perhaps "Hello, Android! I am a string resource!" The entire file should now look like this:
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="hello">Hello, Android! I am a string resource!</string>
        <string name="app_name">Hello, Android</string>
    </resources>
  3. Now open and modify your HelloAndroid class and use the XML layout. Edit the file to look like this:
    package com.example.helloandroid;
    import android.app.Activity;
    import android.os.Bundle;
    public class HelloAndroid extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
    }
    When you make this change, type it by hand to try the code-completion feature. As you begin typing "R.layout.main" the plugin will offer you suggestions. You'll find that it helps in a lot of situations.
    Instead of passing setContentView() a View object, you give it a reference to the layout resource. The resource is identified as R.layout.main, which is actually a compiled object representation of the layout defined in /res/layout/main.xml. The Eclipse plugin automatically creates this reference for you inside the project's R.java class. If you're not using Eclipse, then the R.java class will be generated for you when you run Ant to build the application. (More about the R class in a moment.)
Now re-run your application — because you've created a launch configuration, all you need to do is click the green arrow icon to run, or select Run > Run History > Android Activity. Other than the change to the TextView string, the application looks the same. After all, the point was to show that the two different layout approaches produce identical results.
Tip: Use the shortcut Ctrl-F11 (Cmd-Shift-F11, on Mac) to run your currently visible application.
Continue reading for an introduction to debugging and a little more information on using other IDEs. When you're ready to learn more, read Application Fundamentals for an introduction to all the elements that make Android applications work. Also refer to the Developer's Guide introduction page for an overview of the Dev Guide documentation.

R class

In Eclipse, open the file named R.java (in the gen/ [Generated Java Files] folder). It should look something like this:
package com.example.helloandroid;
public final class R {
    public static final class attr {
    }
    public static final class drawable {
        public static final int icon=0x7f020000;
    }
    public static final class id {
        public static final int textview=0x7f050000;
    }
    public static final class layout {
        public static final int main=0x7f030000;
    }
    public static final class string {
        public static final int app_name=0x7f040001;
        public static final int hello=0x7f040000;
    }
}
A project's R.java file is an index into all the resources defined in the file. You use this class in your source code as a sort of short-hand way to refer to resources you've included in your project. This is particularly powerful with the code-completion features of IDEs like Eclipse because it lets you quickly and interactively locate the specific reference you're looking for.
It's possible yours looks slighly different than this (perhaps the hexadecimal values are different). For now, notice the inner class named "layout", and its member field "main". The Eclipse plugin noticed the XML layout file named main.xml and generated a class for it here. As you add other resources to your project (such as strings in the res/values/string.xml file or drawables inside the res/drawable/ direcory) you'll see R.java change to keep up.
When not using Eclipse, this class file will be generated for you at build time (with the Ant tool).
You should never edit this file by hand.

Debug Your Project

The Android Plugin for Eclipse also has excellent integration with the Eclipse debugger. To demonstrate this, introduce a bug into your code. Change your HelloAndroid source code to look like this:
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Object o = null;
        o.toString();
        setContentView(R.layout.main);
    }
}
This change simply introduces a NullPointerException into your code. If you run your application again, you'll eventually see this:
Press "Force Quit" to terminate the application and close the emulator window.
To find out more about the error, set a breakpoint in your source code on the line Object o = null; (double-click on the marker bar next to the source code line). Then select Run > Debug History > Hello, Android from the menu to enter debug mode. Your app will restart in the emulator, but this time it will suspend when it reaches the breakpoint you set. You can then step through the code in Eclipse's Debug Perspective, just as you would for any other application.

Creating the Project without Eclipse

If you don't use Eclipse (such as if you prefer another IDE, or simply use text editors and command line tools) then the Eclipse plugin can't help you. Don't worry though — you don't lose any functionality just because you don't use Eclipse.
The Android Plugin for Eclipse is really just a wrapper around a set of tools included with the Android SDK. (These tools, like the emulator, aapt, adb, ddms, and others are documented elsewhere.) Thus, it's possible to wrap those tools with another tool, such as an 'ant' build file.
The Android SDK includes a tool named "android" that can be used to create all the source code and directory stubs for your project, as well as an ant-compatible build.xml file. This allows you to build your project from the command line, or integrate it with the IDE of your choice.
For example, to create a HelloAndroid project similar to the one created in Eclipse, use this command:
android create project \
    --package com.example.helloandroid \
    --activity HelloAndroid \ 
    --target 2 \
    --path <path-to-your-project>/HelloAndroid 
This creates the required folders and files for the project at the location defined by the path.
For more information on how to use the SDK tools to create and build projects, please read Developing in Other IDEs.

Java and Ajax

AJAX is now positioned as the 'it' technology and many developers are being forced (sometimes kicking and screaming) into this new world. I have been impressed by the scarce information that I've seen about people using AJAX in real 'non-toy' situations to implement major systems and the issues that are associated with it. I've seen many examples in frameworks such as Echo2 and DWR, but I haven't seen a lot of discussion about what the various pitfalls are of these approaches. I've also not seen anyone do any in-depth analysis of integrating the various java web tier technologies (JSP, WebMacro, FreeMarker, etc) with the AJAX frameworks (DOJO, Scriptaculous, etc).

So if you're an AJAX person, what is your reason for using AJAX? What frameworks are you using to build out your architecture? What tools are you using for development / debugging? And if you can, give us a postmortem of your experiences with a real world project.