Android; Implementing global state; share data between Activities and across your application

If your developing an Android application, chances are you will have multiple activities that perform various tasks. One of my first questions when I was investigating Android, was how can I pass data between my Activities? Moreover, how can I retain some form of state, globally throughout my application, so I can dynamically pass data without having to persist to a datastore between Activities.

The solution; Use the applications Context

Firstly, you should create a new class that will behave as our global object, for example :

package com.jameselsey.domain;

import java.util.ArrayList;
import java.util.List;
import com.google.android.maps.GeoPoint;
import android.app.Application;

/**
* This is a global POJO that we attach data to which we
* want to use across the application
* @author James Elsey
*
*/
public class GlobalState extends Application
{
private String testMe;

public String getTestMe() {
return testMe;
}
public void setTestMe(String testMe) {
this.testMe = testMe;
}
}

The above class declares one String, with accessor methods. Soon we will see how this object will be available throughout the application. You can add anything you want onto this object, in my application I have a List of other domain classes that I wanted to use elsewhere in my application.

Right, now that you have your global class defined, you need to specify this in your AndroidManifest file, otherwise the application won’t know where to find this class, and you will get a ClassNotFoundException

Locate your application tag, and add this into it :

android:name="com.jameselsey.domain.GlobalState"

It must reference your fully qualified global state class

Now you have it set, your ready to start putting data in, and pulling data out, use the following

// Set values
GlobalState gs = (GlobalState) getApplication();
gs.setTestMe("Some String");</code>

// Get values
GlobalState gs = (GlobalState) getApplication();
String s = gs.getTestMe();

And thats it! Off you go!

Converting UK Postcodes to co ordinates to use in Android

If your developing applications on Android, and are looking at using the Maps API, chances are you are going to want to plot items on the map, and in order to do that you need to know the longtitude and latitude of the location you wish to mark.

I’ll assume that you already have a solid base to work from, as in a working Android application with a MapView enabled.

To locate an item on the map you need to use a GeoPoint, example below

private float longtitude;
private float latitude;
GeoPoint p = new GeoPoint((int)(latitude * 1E6), (int)(longtitudel * 1E6));

Notice the usage of float values, the easiest way of getting from a postcode to a co ordinate is to obtain the longtitude and latitude values from a conversion website, and then to add it to the above forumla. The reason being is because it is incredibly difficult to find the int values of a co ordinates, so it is easier to get a float value and convert

In brief, do the following

  1. Go to MyGeoPosition.com and enter your postcode
  2. From the URLs it generates, take the longtitude and latitude values, then enter them in the above float variables
  3. Generate your GeoPoint using the above formula
  4. Start plotting!

Incrementing and Decrementing, the operators

The operators for incrementing and decrementing in Java has been irritating me for some time now, just when I think I understand whats going on, I try a mock exam for SCJP and I get caught out. So I’ve decided to sit down, do a bit of reading, and drill it out.

Take this example, what do you think the output will be?

int a = 1;
int b = 5;
System.out.print("a++ is : " + a++);
System.out.print("++b is : " + ++b);

The output will be :

1
6

Right heres the explanation. We have two things going on here, we have a Postfix(b++) operator and a Prefix(++b) operator.

What this means, in plain and simplest English is as follows

<em>a++ means, use the value of a in the executing statement, THEN increment it</em>

<em>++b means, BEFORE we use the value of b, increment it</em>

So there you have it, if the operator comes before the variable <em>(Prefix)</em>, it means do the incrementing/decrementing before you evaluate the expression in question, and if the operator comes after <em>(Postfix)</em>, then use the current value of the variable, and when thats done, increment it (maybe for use next time, such as in a loop?)

The same works for the decrementing operator, such as –a or a–

Simples

FTP: How to download all files, directories and sub-directories

I’ve recently decided to cancel my hosting package with 1and1, as I don’t really have much use for it any more what with all the freebies Google is dishing out.

I needed to take a backup of all my files, and unfortunately mget doesn’t (or at least at the time) doesn’t support the downloading of directories, luckily there is another tool to help, <a href=”http://en.wikipedia.org/wiki/Wget”>wget</a>.

This example of wget will download all files (the -r specifies recursively) from a directory on the domain

<code>wget -r ftp://account_name:password@mydomain.com/directoryname</code>

JSTL Expressions ignored by Google App Engine, how to fix that..

So, you’ve written a nice J2EE application and have uploaded it onto the GAE only to be upset that your nice variables are displaying as ${contact.firstName} for example? No worries, its a simple issue, GAE seems to ignore expression language by default and all you need to do is to add the following line into your JSPs.

&lt;%@ page contentType=&quot;text/html;charset=UTF-8&quot; language=&quot;java&quot; isELIgnored=&quot;false&quot; %&gt;

Commit that and you’re good to go ;)

Modify your Java web application to run on Google App Engine

So, you have a Java web application that you would like to host somewhere for free, no worries, Google to the rescue. What is Google App Engine? Well to quote from their site…

Google App Engine lets you run your web applications on Google’s infrastructure. App Engine applications are easy to build, easy to maintain, and easy to scale as your traffic and data storage needs grow. With App Engine, there are no servers to maintain: You just upload your application, and it’s ready to serve your users.

You can serve your app from your own domain name (such as http://www.example.com/) using Google Apps. Or, you can serve your app using a free name on the appspot.com domain. You can share your application with the world, or limit access to members of your organization.

Google App Engine supports apps written in several programming languages. With App Engine’s Java runtime environment, you can build your app using standard Java technologies, including the JVM, Java servlets, and the Java programming language—or any other language using a JVM-based interpreter or compiler, such as JavaScript or Ruby. App Engine also features a dedicated Python runtime environment, which includes a fast Python interpreter and the Python standard library. The Java and Python runtime environments are built to ensure that your application runs quickly, securely, and without interference from other apps on the system.

As an overview, you will need to do the following:

  1. Read the GAE Documentation
  2. Download the GAE SDK
  3. Alter your application
  4. Test this locally using the GAE development server (as included with GAE SDK)
  5. If it all works, upload it using the AppCfg command line utility

The GAE SDK

Go ahead and download the GAE SDK, unzip this somewhere on your local hard drive, in my case this was /home/james/Development/utils/appengine-java-sdk-1.2.6

Altering your application

Next, you need to add the app engine libraries to your application, I’m using maven2 purely for ease of use, so I added this to my pom.xml file

        <dependency>
           <groupId>com.google.appengine</groupId>
           <artifactId>appengine-java-sdk</artifactId>
           <version>1.2.6</version>
       </dependency>

When you try to build the application, maven won’t be able to automatically download the jar file, so you’ll have to install that manually using the following command

mvn install:install-file -DgroupId=com.google.appengine -DartifactId=appengine-java-sdk -Dversion=1.2.6 -Dpackaging=jar -Dfile=lib/user/appengine-api-1.0-sdk-1.2.6.jar

You’ll notice that the actual jar file you need is under lib/user/ from the SDK you just downloaded.

You will need to create the appengine-web.xml file, this should reside in the same place as your standard web.xml file, under WEB-INF. The purpose of this file is to inform the GAE which application this belongs to, so you will need to add your GAE application ID into the example below, in my case it was sales-tracker

<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
   <application>sales-tracker</application>
   <version>1</version>
</appengine-web-app>

Provide an empty implementation of MultipartWrapper

The next thing that you need to do is to edit your web.xml to include the MultipartWrapperFactory, add the following into the init-param section

<init-param>
          <param-name>MultipartWrapperFactory.Class</param-name>
          <param-value>com.jameselsey.salestracker.util.EmptyMultipartWrapper</param-value>
      </init-param>

The next thing we need to do is to provide an implementation of the MultipartWrapper, it doesn’t matter where in your package structure you take care of this, providing it matches up to the declaration in your web.xml, as shown above

package com.jameselsey.salestracker.util;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import net.sourceforge.stripes.config.Configuration;
import net.sourceforge.stripes.controller.FileUploadLimitExceededException;
import net.sourceforge.stripes.controller.multipart.MultipartWrapper;
import net.sourceforge.stripes.config.ConfigurableComponent;
import net.sourceforge.stripes.controller.multipart.MultipartWrapperFactory;

/**
* GAE has no support for uploading of files, so we use this to disable that part of Stripes
*
* @author james.elsey
*/
public class EmptyMultipartWrapper implements ConfigurableComponent, MultipartWrapperFactory {

  /**
   * @see net.sourceforge.stripes.config.ConfigurableComponent#init(net.sourceforge.stripes.config.Configuration)
   */
  public void init(Configuration conf) throws Exception {
  }

  /**
   * @see net.sourceforge.stripes.controller.multipart.MultipartWrapperFactory#wrap(javax.servlet.http.HttpServletRequest)
   */
  public MultipartWrapper wrap(HttpServletRequest request) throws IOException, FileUploadLimitExceededException {
      return null;
  }
}

Upload your project to GAE

Your application should be ready to go now, build your application using

mvn clean package

Then upload it to GAE using, you have to update the war folder not the actual war file


./AppCfg.sh update ~/Development/projectname/target/myprojectname

Thats pretty much it! Good luck!

Setting up a basic Stripes framework

After being introduced to Struts1, Struts2 and SpringMVC at a very early stage in my development career, I was very happy to work on a project with Stripes. Stripes can do nearly everything I was doing with other action based frameworks, but is much simpler to use but is also a very versatile framework.

I’ve decided to put together this tutorial on how to setup a basic Stripes project with one page and one action, this will give you an idea of how the framework fits together, you can then expand on it as you wish.

Stripes is a very easy to use J2EE framework, similar to Struts but without all the heavy configuration XML files. Lets have a look at how easy it is to setup

Firstly, grab hold of an IDE such as Netbeans. Install the standalone Maven, or use the embedded version that comes with Netbeans (or just grab the plugin). I won’t go into how to set this up right now, so you’ll have to figure that out yourself.

Once that’s setup, in Netbeans go File > New Project, choose a Maven Web project. This should give you a basic skeleton of a project.

So far, your new application has no idea about stripes, so we can go ahead and fix that, this is where we benefit from using Maven.

Open up the pom.xml that is located under Project Files, and add the following into the dependencies section. What this does is to imply that our project is going to make use of the stripes, jstl and taglibs libraries. Maven will detect this and upon saving will add those libraries to our project.

<dependency>
  <groupid>net.sourceforge.stripes</groupid>
  <artifactid>stripes</artifactid>
  <version>1.5.1</version>
</dependency>
<dependency>
  <groupid>jstl</groupid>
  <artifactid>jstl</artifactid>
  <version>1.1.2</version>
</dependency>
<dependency>
  <groupid>taglibs</groupid>
  <artifactid>standard</artifactid>
  <version>1.1.2</version>
</dependency>

The only XML configuration you’ll need to worry about (apart from pom.xml, but that doesn’t count) is the standard web.xml file that’ll be present in any Java web application, go ahead and add the following into your web.xml file, it’ll be located under WEB-INF

<?xml version="1.0" encoding="UTF-8"?>
  <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>MyProject</display-name>
    <filter>
      <filter-name>StripesFilter</filter-name>
      <filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
      <init-param>
        <param-name>ActionResolver.Packages</param-name>
        <param-value>com.jameselsey.myproject.action</param-value>
      </init-param>
    </filter>
    <servlet>
      <servlet-name>DispatcherServlet</servlet-name>
      <servlet-class>net.sourceforge.stripes.controller.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
    </servlet>
    <filter-mapping>
      <filter-name>StripesFilter</filter-name>
      <servlet-name>DispatcherServlet</servlet-name>
      <dispatcher>REQUEST</dispatcher>
      <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    <servlet-mapping>
      <servlet-name>DispatcherServlet</servlet-name>
      <url-pattern>*.action</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
      <welcome-file>/WEB-INF/jsp/hello.jsp</welcome-file>
    </welcome-file-list>
  </web-app>

Firstly, we declare a StripesFilter and specify which class it is from, this is part of the standard stripes setup so we can ignore that, however pay special attention to the ActionResolver parameter, that needs to match the “root” of our actions package, but we’ll come into that later.

Next we’ll need a DispatcherServlet declaration, and then we need to map stripes to intercept all requests via the DispatcherServlet. We also need to inform the servlet to filter all requests for .action. Lastly, we can specify a default page to be loaded when the application starts.

So now we have the stripes library available to us, so lets create an action and jump right in.

Create a new java class, such as com.jameselsey.action.MyHelloAction. Notice how I’ve put the action under the “action” package, the reason for this is so I can specify that package as the “root” action package in the web.xml file (check the web.xml code I posted above, the MyHelloAction will be available because it is within the package set in the ActionResolver)

Add the following into your action, you can rename variables if you like


import java.util.Date;
import java.util.Random;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;

public class MyHelloAction implements ActionBean 
{

	private ActionBeanContext ctx;

    	public ActionBeanContext getContext() 
	{        
		return ctx;    
	}

    	public void setContext(ActionBeanContext ctx) 
	{        
		this.ctx = ctx;    
	}    

	private Date date;

	public Date getDate() 
	{        
		return date;    
	}

    	@DefaultHandler    
	public Resolution currentDate() 
	{        
		date = new Date();        
		return new ForwardResolution(VIEW);    
	}

    	public Resolution randomDate() 
	{        
		long max = System.currentTimeMillis();        
		long random = new Random().nextLong() % max;        
		date = new Date(random);        
		return new ForwardResolution(VIEW);    
	}    
	
	private static final String VIEW = "/WEB-INF/jsp/hello.jsp";

}

This action will generate a date, and a random date. Notice that the currentDate method is the default handler, that means that if we come into this action and don’t specify what event we want, the currentDate will be called. This would generate a date, and then return a forward resolution. You can see at the bottom of the action we have setup a String which contains the resolution to return, in this case a JSP

Right, so now we have our action which has generated some data for us, now lets setup a JSP to display this to a user. Create a jsp called hello.jsp under WEB-INF/jsp, add the following

<%@page contentType="text/html;charset=ISO-8859-1" language="java" %>
<%@taglib prefix="s" uri="http://stripes.sourceforge.net/stripes.tld" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"    "http://www.w3.org/TR/html4/strict.dtd" >
        <html>
          <head>
            <title>Hello!</title>
          </head>
          <body>
            <h3>Hello James Elseys' Stripes Tutorial!</h3>
            <p>
              <b>
                <fmt:formatDate type="both" dateStyle="full"                                value="${actionBean.date}" />
              </b>
            </p>
            <p>
              <s:link beanclass="com.jameselsey.myproject.action.MyHelloAction"                    event="currentDate" >Show the current date and time</s:link>
              <s:link beanclass="com.jameselsey.myproject.action.MyHelloAction"                    event="randomDate" >Show a random date and time</s:link>
            </p>
          </body>
        </html>

Firstly, our JSP displays a date. As we have set a @DefaultHandler on our action, the currentDate gets served up in the JSP.

Underneath we have 2 links that go to our action class, these aren’t regular anchor links, we are making use of the stripes tags here. This allows us to bind a link to an action class, and to also specify an event. The event should match up to a method in the action class.

You should have a file structure as follows, double check that your files are in the correct place

Once your all set, try and run the application! You should get something as in my following screenshot. Its now up to you to add more actions, pages, and other features such as Data Access Objects

Thanks for reading this post, apoligies for keeping it brief but I just wanted to note down how to setup the framework while its still fresh on my mind! I’ll try to keep more posted in the future as I’m starting my own google-code hosted project using stripes. If you’ve got anything to add, or need some help, please feel free to let me know!

Slackware 13.0 Installation : Part 1, pre-install

Slackware, which I like to refer to as “proper linux”, theres no messing around with fancy wizards, this is hardcore linux; and a good cure for insomnia (second to Linux From Scratch that is)

This should help you get Slackware 13 installed, I did all of this using Virtual Box so make sure you have that installed first, and have created an environment ready for slackware.

Insert your LiveCD, or mount your downloaded ISO onto Virtual Box, then start up the virtual machine. Once virtual box has loaded up it should bring you to the first welcome screen in the Slackware 13 installation.

Just press enter at the first screen, as we’re just doing a basic install we won’t need any advanced parameters.

The next prompt you’ll receive, just select to use the default keyboard map.

You will next be presented with some information about how to begin the installation, and be asked to login as root. Go ahead and type root, you’ll then be ready to start installing.