Archive for the ‘tutorial’ Category

How to add sliding transitions between Canvas in J2ME

Monday, June 23rd, 2008

Today we’ll see a simple way to add sliding transition between Canvas in a Java ME application. Just take a look at it in the emulator page to see how it performs: Canvas sliding transitions in action!

j2me canvas sliding transition screenshot

The source code

FxBaseCanvas

First of all, we know that Canvas paint() method is protected, so, to access it from the class we’ll build, we must extend its visibility by extending Canvas class itself. We’ll do it by defining our FxBaseClass in this simple way:

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
 
public class FxBaseCanvas extends Canvas
{
	public void paint(Graphics g)
	{
	}
}

CanvasSlideFx

Now, we start building our CanvasSlideFx class, that will extend Canvas itself. We start defining some useful properties:

// time related properties
long startTime = 0;
long duration = 0;
 
// current state of the transition
boolean running = false;
 
// direction of sliding
int direction = LEFT;
 
// the previous and next Canvas instances
FxBaseCanvas fromCanvas = null;
FxBaseCanvas toCanvas = null;
 
// the current Display object
Display display = null;
 
// properties used to correctly place the 2 Canvas
int deltaX = 0;
int deltaY = 0;

Now, we define our class constructor, that will initialize coordinate properties according to the specified transition direction. The detailed argument list is:

  • The current Display object, that will be used to retrieve the current displayed Canvas, and to set the next one
  • The destination Canvas, that will extend the previously defined FxBaseCanvas class
  • The transition direction (one of Canvas.UP, RIGHT, DOWN or LEFT)
  • The transition duration, in milliseconds
public CanvasSlideFx(Display display, FxBaseCanvas toCanvas, int direction, long duration)
{
	this.display = display;
	this.fromCanvas = (FxBaseCanvas)display.getCurrent();
	this.toCanvas = toCanvas;
	this.direction = direction;
	this.duration = duration;
 
	switch(direction)
	{
	case UP:
		deltaY = - getHeight(); break;
	case RIGHT:
		deltaX = getWidth(); break;
	case DOWN:
		deltaY = getHeight(); break;
	case LEFT:
		deltaX = - getWidth(); break;
	}
}

Now, we define a startTransition() method, that will actually start the animation. To implement the animation itself, we let our class implement Runnable.

void startTransition()
{
	this.startTime = System.currentTimeMillis();
 
	running = true;
 
	new Thread(this).start();
}

And here’s the run() method implementation, that we must implement from Runnable interface. As long as the animation is running, we will repaint our animated Canvas, with a given interval of 50 milliseconds (but you can freely change this). When it finishes (so, running is false), we will exit the main loop and set the current Displayable to our toCanvas.

public void run()
{
	try
	{
		while(running)
		{
			repaint();
 
			synchronized(this)
			{
				wait(50L);
			}
		}
	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
	display.setCurrent(toCanvas);
}

Finally, we have our paint() method, that will actually paint our transition. It will do this by painting both the source and the destination Canvas, translating them according to the transition direction, and to the elapsed time.

protected void paint(Graphics g)
{
	if(!running)
		startTransition();
 
	long diff = System.currentTimeMillis() - startTime;
 
	if(diff >= duration)
	{
		running = false;
 
		diff = duration;
	}
 
	int perc = (int)(100 * diff / duration);
 
	int dx = deltaX * perc / 100;
	int dy = deltaY * perc / 100;
 
	g.translate(dx, dy);
 
	fromCanvas.paint(g);
 
	g.translate(- deltaX, - deltaY);
 
	toCanvas.paint(g);
 
	g.translate(deltaX - dx, deltaY - dy);
}

How to use it?

Now we’ll see how to integrate the CanvasSlideFx within an existing code that already uses Canvas.
So, let’s assume that our application currently has, somewhere in its code, these lines:

MyCanvas firstCanvas = new MyCanvas();
 
Display.getDisplay(myMidlet).setCurrent(firstCanvas);
...
//and somewhere else
MyOtherCanvas secondCanvas = new MyOtherCanvas();
 
Display.getDisplay(myMidlet).setCurrent(secondCanvas);

where MyCanvas and MyOtherCanvas will likely extend Canvas.

Now here are the required steps to integrate transitions in our code:

  1. First of all, we must make MyCanvas and MyOtherCanvas extend FxBaseCanvas instead of directly Canvas. So, we’ll have:
    public class MyCanvas extend FxBaseCanvas ...
  2. Then, let’s say we want to animate the transition between firstCanvas and secondCanvas, we will remove the code:
    Display.getDisplay(myMidlet).setCurrent(secondCanvas);

    and replace it with:

    CanvasSlideFx fxCanvas = new CanvasSlideFx(
    	Display.getDisplay(myMidlet),
    	secondCanvas,
    	Canvas.LEFT,
    	500L
    );
     
    Display.getDisplay(myMidlet).setCurrent(fxCanvas);
  3. and we’ve done it! :)

Resources and download

You can download the code explained in this article with the following links:

How to create a color fading text in J2ME

Wednesday, June 18th, 2008

It’s time for new effects! :)

Today we’ll see how to implement and and use text that changes multiple colors with a fading effect. You can see it in action here: J2ME text color fade effect in action.

Color Fading Text screenshot

So, let’s start defining our ColorFadeText class.

The code

We start defining the necessary properties:

//will hold the colors to fade
int[] colors = null;
 
//duration of a single fade
int fadeDuration = 0;
 
//effect start time
long startTime = 0;
 
//property used to check if effect has started
public boolean started = false;
 
//the text to be drawn
String text = null;

Now, we define the main constructor, that will accept the following arguments:

  • the text to be drawn
  • an int[] array containing the colors to fade into
  • the duration of a single fade
public ColorFadeText(String text, int[] colors, int fadeDuration)
{
	if(colors.length == 0)
	{
		throw new IllegalArgumentException("You must define at least 1 color");
	}
	this.text = text;
	this.colors = colors;
	this.fadeDuration = fadeDuration;
}

The effect start() method will simply set the startTime value to current time and the started property to true

public void start()
{
	startTime = System.currentTimeMillis();
 
	started = true;
}

Then, we have the paint() method, that will be used to paint the text on the given Graphics instance:

public void paint(Graphics g, int x, int y, int anchor)
{
	if(started)
	{
		long diff = System.currentTimeMillis() - startTime;
 
		int module = (int)(diff % fadeDuration);
 
		int colorIndex = (int)(diff / fadeDuration) % colors.length;
 
		int midColor = midColor(
			colors[(colorIndex + 1) % colors.length],
			colors[colorIndex],
			module,
			fadeDuration
		);
 
		g.setColor(midColor);
	}
	else
	{
		g.setColor(colors[0]);
	}
 
	g.drawString(text, x, y, anchor);
}

The following utility method will be the one actually used to get the current text color:

static int midColor(int color1, int color2, int prop, int max)
{
	int red =
		(((color1 >> 16) & 0xff) * prop +
		((color2 >> 16) & 0xff) * (max - prop)) / max;
 
	int green =
		(((color1 >> 8) & 0xff) * prop +
		((color2 >> 8) & 0xff) * (max - prop)) / max;
 
	int blue =
		(((color1 >> 0) & 0xff) * prop +
		((color2 >> 0) & 0xff) * (max - prop)) / max;
 
	int color = red << 16 | green << 8 | blue;
 
	return color;
}

How to use it?

Using the ColorFadeText object is quite simple, since it’ll be very similar to use a common String. Just follow this plain steps.

1. Create a ColorFadeText instance

ColorFadeText text = new ColorFadeText(
	"I'M A FADING TEXT!",
	new int[]{0xff0000, 0x00ff00, 0x0000ff, 0xff00ff},
	1000
);

2. Start it…

text.start();

3. And then, in your Canvas paint() method, paint it, using the same arguments used by Graphics drawString() method (adding a reference to the Graphics instance of course):

text.paint(g,
	getWidth() / 2,
	2,
	Graphics.HCENTER | Graphics.TOP
);

Just a side note: since it’s an animated effect, you’ll need to repaint it quite frequently, so, for example, you can use a Thread to periodically call Canvas repaint() method.

Source code download

You can download source code of ColorFadeText, and of a sample Canvas that makes use of it:

This article is also available on Forum Nokia Wiki: How to create a color fading text in Java ME.

Displaying GPS position in FlashLite using Google Static Maps and KuneriLite

Thursday, June 12th, 2008

Today’s tutorial is about using Google Maps static images, and GPS data, to display maps in a FlashLite application using KuneriLite.

FlashLite KuneriLite Google Maps application screenshot

Prerequisites

Get your own Google Maps API key

To use Google Maps services, you should have a Google Maps API key. If you do not have one, you can go here:

http://code.google.com/apis/maps/signup.html

and signup for your API key.

Download and install KuneriLite

KuneriLite is a tookit that extends FlashLite capabilites allowing applications to access native Symbian functionalities, like file writing, or reading GPS data.

To proceed in this tutorial, you must download and install KuneriLite: KuneriLite download page.

Create FlashLite application

Create your FlashLite movie

In this example, we’ll use FlashLite 2.1, but porting it to other (older or newer) FlashLite versions will be quite straightforward. So, after you’ve created an empty FlashLite movie, follow this simple steps:

  • Create a Button by going to Insert -> New Symbol…
  • enter GpsButton as name
  • check the Export for ActionScript and Export in first frame checkboxes

GpsButton properties

  • Now, design your Button as you prefer, for example placing a big “Find me!” label on it
  • After you’ve finished designing your Button, place it on movie root, in the lower part of the stage, as in the attached screenshot, and give it startButton as Instance Name

Place GpsButton on stage

Enter ActionScript code

On movie root, create a new layer called Actions, and open its ActionScript editor. We’ll start defining some properties:

// Enter your api key here
var apiKey = 'API_KEY';
 
//If you're using non-commercial version of KuneriLite, you'll not need to change this
var kuneriPath = 'http://127.0.0.1:1001/Basic/';

Now, we’ll define some useful functions that we’ll use in our code:

//We'll call this function when some KuneriLite related errors occur
function kuneriError(error:String)
{
	trace("KuneriLite error: " + error);
}
 
//This function will do all calls to KuneriLite servers
//and call the given handler passing response values as argument
function kuneriLoad(url, handler)
{
	var loader:LoadVars = new LoadVars();
 
	loader.onLoad = function()
	{
		handler(this);
	}
	trace("LOADING: " + url);
 
	loader.load(url);
}

Now, let’s code the Button-related logic. When the user presses the startButton we want to:

  • start the GPS
  • retrieve the current GPS position
  • display a map centered in the retrieved GPS position

To get full infos about about KuneriLite GPS plugin, you can check the related Wiki page: http://wiki.kunerilite.net/index.php?title=GPS_plugin

We begin starting the GPS on gpsButton press, using the start klCommand:

startButton.onPress = function()
{
	kuneriLoad(kuneriPath + 'GPS?klCommand=start', gpsStarted);
}
function gpsStarted(res:LoadVars)
{
	if(res.klError == 0 || res.klError == -11)
	{
		trace("GPS started");
 
		kuneriLoad(kuneriPath + 'GPS?klCommand=read', gpsDataRead);
	}
	else
	{
		kuneriError("Error starting GPS!");
	}
}

The gpsStarted() handler will:

  • check if there is no error (klError = 0) or if GPS is already started (klError = -11). For full errors list associated with GPS plugin, check KuneriLite Wiki page: http://wiki.kunerilite.net/index.php?title=GPS_plugin
  • if there’s an error starting the GPS, call our kuneriError() function defined above
  • if GPS is correctly started, it will make a second call to KuneriLite, this time to retrieve current GPS position (klCommand=read)

This second call to KuneriLite will call gpsDataRead() handler, defined below:

function gpsDataRead(res:LoadVars)
{
	if(res.klError == 0)
	{
		if(res.klPosLatitude != undefined)
		{
			var lat = res.klPosLatitude;
			var lng = res.klPosLongitude;
 
			trace("POSITION: " + lat + ", " + lng);
 
			loadMap(lat, lng);
		}
		else
		{
			kuneriLoad(kuneriPath + 'GPS?klCommand=read', gpsDataRead);
		}
	else
	{
		kuneriError("Error retrieving GPS position!");
	}
}

This handler, as above, will check if there is any error raised by KuneriLite and, if not, will check if latitude and longitude coordinates are available, by checking response klPosLatitude and klPosLongitude property values. If they’re not available, a new call to read klCommand is done, otherwise the following loadMap() function is called.

function loadMap(lat:Number, lng:Number)
{
	var mapClip:MovieClip = _root.createEmptyMovieClip('mapClip', _root.getNextHighestDepth());
 
	mapClip._x = 0;
	mapClip._y = 0;
 
	var mapWidth = 240;
	var mapHeight = 280;
 
	var loader:MovieClipLoader = new MovieClipLoader();
 
	var mapUrl:String = 'http://maps.google.com/staticmap?center=' +
		lat + ',' + lng + '&amp;format=jpg&amp;zoom=8&amp;size=' +
		mapWidth + 'x' + mapHeight + '&amp;key=' + apiKey;
 
	loader.loadClip(mapUrl, mapClip);
}

The above function:

  • attaches a new empty movie clip to movie root
  • places it to coordinates (0,0)
  • use a MovieClipLoader to load a 240×280 map image, in jpeg format, in the empty clip

Done that, you can actually test your FlashLite movie

Test your FlashLite application

Test on PC

To test your application without deploying on real device, you must follow these simple steps:

  • Start KuneriLite emulator with default settings (port: 1001, key: Basic)
  • Start your FlashLite movie
  • Press Find Me! and wait for your image to be loaded (of course, being an emulator, the GPS position will be not real :))

For more infos about KuneriLite Emulator, you can go here: KuneriLite Emulator Wiki page

Test on real device

To test your app on real device, you must package your SIS application using KuneriLite Wizard, following these steps:

KuneriLite Emulator screenshot

  • Export your FlashLite movie
  • Create a new KuneriLite project
  • Enter application name and other data, checking GPS from the available plugins
  • Check “Use external player” option if you developed for a development player (2.x or 3.x) and would like to launch the application using one of those players
  • It is also recommended to always check “Use stub” option
  • Select the exported SWF as project Main SWF

Note: to use GPS you should sign your application, specifying certificate, key and password in KuneriLite Wizard interface. Otherwise, your application will not be able to access GPS functionalities.

For more infos about KuneriLite Wizard, you can go here: KuneriLite Wizard Beginner’s Guide

Source code and resources

J2ME Google Maps API is article of the week on Forum Nokia!

Monday, June 9th, 2008

I’m really happy to announce that my J2ME Google Maps API article on Forum Nokia Wiki has been selected as Article of the Week! :)

J2ME Google Maps API Article of the Week

And, to celebrate this event, I’ve added a brand new feature to my article that will allow you to:

  • create larger tiled maps
  • support map scrolling

How does it work?

You start instantiating a GoogleMaps object as usual:

GoogleMaps gMap = new GoogleMaps("API_KEY");

Then you get your map, for example geocoding a given address:

double[] coords = gMap.geocodeAddress("Leicester square, London");
 
Image mapImage = gMap.retrieveStaticImage(
	150, 150,
	coords[0], coords[1],
	12, "png"
);

Then, let’s say you want to scroll your map 100 pixels up, what you’ll do is:

double[] newCoords = gMap.adjust(
	coords[0], coords[1],
	0, -100, 12
);
 
Image newMapImage = gMap.retrieveStaticImage(
	150, 150,
	newCoords[0], newCoords[1],
	12, "png"
);

As you’ve seen, the adjust method takes these arguments:

  • the current latitude and longitude
  • the deltaX and deltaY, in pixels
  • the current zoom level

and returns the new map center latitude and longitude coordinates.

You can check the full updated source code on Forum Nokia Wiki article: J2ME Google Maps API, and a full-featured example, with the scrolling feature, on the emulator page: J2ME Google Maps API in action.

J2ME Image effects part 2: sliding transitions

Thursday, May 22nd, 2008

After an explosive J2ME class, now it’s the time for sliding transition effects. With the following SlidingImage class you’ll be able to seamlessly add both SlideIn and SlideOut effects to your toooo static apps!

J2ME sliding transition effect screenshot

As usual, take a look at how this would appear in a real phone, and then proceed with the simple these 1,2,3 steps :)

  1. Download and include in your code the SlidingImage.java class
  2. Instantiate a new SlidingImage:
    SlidingImage image = new SlidingImage(
    	Image.createImage("/image1.png"),
    	10,
    	SlidingImage.SLIDE_OUT);

    These are the constructor arguments:

    • An Image object to be slided
    • The number of pieces of the sliding image
    • The type of slide, can be SlidingImage.SLIDE_IN or SlidingImage.SLIDE_OUT
  3. Start the sliding effect, specifying its direction and duration (in milliseconds):
    image.slide(Canvas.RIGHT, 3000);

    Direction can be one of Canvas properties UP, RIGHT, DOWN and LEFT.

  4. Now you can paint it simply specifying coordinates and an anchor, as usual:
    image.paint(g,
    	100, 100,
    	Graphics.HCENTER | Graphics.VCENTER);
  5. If you remember ExplodingImage class, you can check if effect is ended with the public ended property:
    if(image.ended)
    {
    //effect-end related code
    }
  6. If you want to reset the effect, also changing the sliding image pieces and effect type (slide in or out), you can use the reset() method:
    //to reset changing also slides and type properties
    image.reset(12, SlidingImage.SLIDE_IN);
    //otherwise, to simply reset:
    image.reset();

You can download source code here:

Let your images explode in J2ME!

Tuesday, May 20th, 2008

After a MIDP 1.0 utility to rotate images now time has come for some image fun :)

J2ME Image explode effect screenshot
When writing mobile applications, it’s always cool to add some effects or transitions. But, while for example FlashLite has a nice builtin support for them, with J2ME you have to hand-code even the simplest movement (and this is the main reason why most J2ME apps are all but attractive).

So, here’s a first class that you can use to add an “explode” effect to images in a straightforward way. How to do it? Here we come:

  1. Download the ExplodingImage.java source code and put it straight in your project
  2. Instantiate an ExplodingImage this way:
    //get your Image
    Image sourceImage = Image.createImage("/image.png");
    //and then use it in ExplodingImage constructor
    ExplodingImage image = new ExplodingImage(sourceImage , 5, 8, 8);

    The ExplodingImage constructor accepts the following arguments:

    • An Image instance
    • An int representing the “level” for the exploding effect, that is the strength of the effect itself (higher the level, stronger the effect).
    • The last 2 int arguments represent the horizontal and vertical pieces of the exploded image.
  3. Start the explode effect with the explode() method, that will accept the effect duration as argument:
    image.explode(2000L);
  4. To paint it, simply use its paint() method, very similary to the Graphics drawImage() one. For example, in a Canvas paint() method, you can do something like this:
    protected void paint(Graphics g)
    {
    	g.setColor(0xffffff);
    	g.fillRect(0, 0, width, height);
    	image.paint(g, getWidth() / 2, getHeight() / 2, Graphics.HCENTER | Graphics.VCENTER);
    }

    To give the effect a “smooth” animation, you should paint it quite frequently (let’s say, not once per second :)). So, always using Canvas, a sample code could be like this:

    public void run()
    {
    	while(true)
    	{
    		repaint();
     
    		try
    		{
    			synchronized(this)
    			{
    				wait(50L);
    			}
    		}
    		catch(Exception e)
    		{
    			e.printStackTrace();
    		}
    	}
    }
  5. To test if the effect has ended, you can simply access your ExplodingImage ended instance variable:
    if(image.ended)
    {
    	//effect-end related code
    }
  6. And you’re done! See it in action here: J2ME image explode effect in action

Sample source code is available here:

Rotating images in J2ME using MIDP 1.0

Monday, May 19th, 2008

So you’re still using MIDP 1.0 uh? And maybe you need to rotate an image?

J2ME rotate image screenshot

If this is your case, you could find useful this simple function:

public static Image rotateImage(Image image, int angle) throws Exception
{
	if(angle == 0)
	{
		return image; 
	}
	else if(angle != 180 && angle != 90 && angle != 270)
	{
		throw new Exception("Invalid angle");
	}
 
	int width = image.getWidth();
	int height = image.getHeight();
 
	int[] rowData = new int[width];
	int[] rotatedData = new int[width * height];
 
	int rotatedIndex = 0;
 
	for(int i = 0; i < height; i++)
	{
		image.getRGB(rowData, 0, width, 0, i, width, 1);
 
		for(int j = 0; j < width; j++)
		{
			rotatedIndex = 
				angle == 90 ? (height - i - 1) + j * height : 
				(angle == 270 ? i + height * (width - j - 1) : 
					width * height - (i * width + j) - 1
				);
 
			rotatedData[rotatedIndex] = rowData[j];
		}
	}
 
	if(angle == 90 || angle == 270)
	{
		return Image.createRGBImage(rotatedData, height, width, true);
	}
	else
	{
		return Image.createRGBImage(rotatedData, width, height, true);
	}
}

So, how can you use it? Nothing more than:

Image original = Image.createImage("/original_image.png");
 
Image rotated_image = rotateImage(original, 90);

A J2ME Calendar for all your Canvas!

Friday, May 16th, 2008

You know that J2ME support for Canvas is quite ridiculous.. One list, some form items, and stop. Canvas is left to its terrible destiny, with nothing more than a couple of lines and circles.. isn’t it sad?
So, after this melodramatic introduction, we’re ready for today’s code: a fully featured, customizable, Canvas based calendar!

J2me Canvas Date Picker screenshot

If you prefer a live demonstration rather than a simple screenshot, just go here: Canvas Calendar in action.

So, how to use it?

  1. Download its source code (CalendarWidget.java) and put it straight in your project
  2. Instantiate it within your Canvas with its plain-old-unique constructor:
    CalendarWidget calendar = new CalendarWidget(new Date());
  3. Customize it with the colors/fonts/padding you prefer:
    calendar.headerFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_LARGE);
    calendar.weekdayFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
    calendar.weekdayBgColor = 0xccccff;
    calendar.weekdayColor = 0x0000ff;
    calendar.headerColor = 0xffffff;
  4. After you’ve customized it, remember to always call its initialize() method:
    calendar.initialize();
  5. Now, to paint it, you can simply call its paint() method from your Canvas paint(), like this:
    protected void paint(Graphics g)
    {
        g.setColor(0xffffff);
        g.fillRect(0, 0, getWidth(), getHeight());
        calendar.paint(g);
    }
  6. Now you must allow users to interact with it, so you can, for example, use Canvas keyPressed() method to interact with calendar:
    protected void keyPressed(int key)
    {
        int keyCode = getGameAction(key);
        if(keyCode == FIRE)
        {
            Display.getDisplay(midlet).setCurrent(
                new Alert("Selected date", calendar.getSelectedDate().toString(), null, AlertType.CONFIRMATION)
            );
        }
        else
        {
            calendar.keyPressed(keyCode);
            repaint();
        }
    }

    As you see, what we do is this:

    • if the user press FIRE button, we alert the current selected date
    • otherwise we call calendar keyPressed() method, to make it behave accordingly
  7. Other customizable properties include:
    • MONTH_LABELS: change this to customize month labels in your own language
    • WEEKDAY_LABELS: as above, change this to customize weekday labels
    • startWeekday: this represents the week starting day, and its values range goes from 0 (for Monday) to 6 (for Sunday)

You can download source code of the example described above here: CalendarCanvas.java.

To get some more details about CalendarWidget source code, you can take a look at my article on Forum Nokia Wiki: Building a J2ME Canvas based Calendar / Date picker.

How to parse a generic XML file in J2ME with kXML

Thursday, May 15th, 2008

Some days ago I’ve posted J2ME code to parse RSS feeds using kXML library. Today’s code is about parsing a generic XML, so you can use it to parse any XML document you want. Code is splitted in the following two classes.

XmlNode class

This is the class representing a single node. We’ll define 2 node types:

  • Text nodes: nodes without a name, contanining only a textual value. For them we’ll define a TEXT_NODE final variable
  • Element nodes: nodes with a tag name, that can have children nodes and/or attributes

XmlNode class source code is available here: XmlNode.java

GenericXmlParser class

This is the class that will actually do XML parsing. We’ll define only one public method, parseXML(), that will accept 2 arguments:

  • a KXmlParser instance, that will be used to do XML parsing
  • a boolean that will tell if whitespace-only text nodes must be ignored or not

and will return and XmlNode representing the root node of the parsed XML tree.

GenericXmlParser class source code is available here: GenericXmlParser.java

Sample usage

Let’s see how we can use the two classes above. First we must instantiate and initialize a KXmlParser, and then we can call our GenericXmlParser parseXML() method.

InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream("/test3.xml"));
 
KXmlParser parser = new KXmlParser();
 
parser.setInput(reader);
 
GenericXmlParser gParser = new GenericXmlParser();
 
XmlNode xml = gParser.parseXML(parser, true);

Now, we have our resulting XmlNode that will hold the whole XML tree. We can make a simple dump of it to check if it’s all ok, using this test function:

void dumpXML(XmlNode node, int deep)
{
	for(int i = 0; i < deep; i++)
	{
		System.out.print(" ");
	}
	System.out.print(node.nodeName + " - ");
 
	if(node.nodeValue != null)
	{
		System.out.print("(" + node.nodeValue + ") - ");
	}
	String[] attributes = node.getAttributeNames();
 
	for(int i = 0; i < attributes.length; i++)
	{
		System.out.print(attributes[i] + ": " + node.getAttribute(attributes[i]) + ", ");
	}
 
	System.out.println();
 
	for(int i = 0; i < node.children.size(); i++)
	{
		dumpXML((XmlNode)node.children.elementAt(i), deep + 1);
	}
}

Note: This article is available also on Forum Nokia Wiki: How to parse an XML file in J2ME with kXML

How to use Google Maps data within your mobile application

Wednesday, May 14th, 2008

Note: You can find this article also on Forum Nokia Wiki: How to use Google Maps data in mobile applications

Today we’ll see how to use Google Maps data within a mobile application.
Google Maps offers REST services that allows accessing its data with simple HTTP requests, so we can easily integrate them within our mobile apps.

Signup for a Google Maps API key

First thing you must do is to signup on this page:
http://code.google.com/apis/maps/signup.html
Once done, you’ll get a key (a simple String) you’ll use for all your query to Google Maps services

Static maps

Standard Google Maps code is suited for web applications, since it includes alot of Ajax functionalities, that are not really useful if you’re building a mobile application. So, the solution is to use static maps service, that will allow us to retrieve single images, easily usable within our apps.

Static maps service supports different image formats (png32, gif, jpg) and customizable image size, so that we can get perfect images for all our needs. As an example, suppose we want to retrieve the location at:

  • latitude: 41.867878
  • longitude: 12.471516

We can simply retrieve this URL with an HTTP GET request:

http://maps.google.com/staticmap?center=41.867878,12.471516&
format=png32&zoom=8&size=240x320&key=<API_KEY>

This way, we’ll get a PNG32 image, with a width of 240 pixels, and a height of 320, centered at point (41.867878,12.471516), and with a zoom level of 8 (zoom can go from 0 to a maximum level of 19).

Google Maps static image sample

Geocode an address

From Google Maps docs:
Geocoding is the process of converting addresses (like “1600 Amphitheatre Parkway, Mountain View, CA”) into geographic coordinates (like latitude 37.423021 and longitude -122.083739)

So, let’s assume we want to build an application that displays the address typed by our user. We should firstly geocode its address to geographics coordinates.
To do this, Google Maps offer another REST service easily accessible with simple HTTP requests.

Let’s say you want to geocode this address “Leicester Square, London”, then you’ll request this URL:

http://maps.google.com/maps/geo?q=Leicester%20Square,%20London
&output=csv&key=<API_KEY>

and you’ll get this output:

200,6,51.510605,-0.130728

Where:

  • the first number is a code, that in this case (200) means that geocoding has been successfull (for a full list of status codes you can see here: [1])
  • the second number gives a measure of geocoding accuracy (from 0 to 9 - maximum accuracy)
  • 3rd and 4th numbers represent latitude and longitude of the geocoded address, so these are the coordinate we’ll use to retrieve the map through the static map service we’ve seen before

As you can see, there is an ‘output’ parameter within the geocode request, and this means that we can choose the output format we prefer for our needs. Supported formats are:

  • xml
  • kml (same as xml, but with different Content-Type)
  • json (not really useful for mobile apps)
  • csv (comma separated values)

Proxy server, usage limits

Since your Google Maps API key is bound to a specific URL, to access map services you should setup a proxy server that will receive HTTP requests from your mobile application and forward them to Google Maps REST URLs, giving back Google responses to mobile clients.

Also, be aware that there is a limit to the number of requests (both for static maps and geocode service) you can do each day. For personal uses they’re more than enough, anyway consider this point if you plan to develop commercial services.

Google Maps J2ME API and sample application

Now, you want code right? :) Here it is:

Google Maps sample application screenshot