Search This Blog

Wednesday, September 22, 2010

A simple GPS monitor in j2me with google maps support.

Application without google maps : 
This is a simple application that shows the device's current location coordinates on the screen. It can be built in four easy steps - 
1)Creating a canvas for displaying results. 
2)Starting a new thread so that it doesn't slow down our application. 
3)Using Location Provider object to retrieve the coordinates. 
4)Displaying the coordinates on the canvas. 

MyCanvas a canvas inherited class, which has a paintMe() function that takes 3 parameters, can be called whenever we need to refresh the screen with new data. In this case we are not using google maps so image passed can be anything else or null. LocationProvider is a class that is used to obtain gps data from the device. 
Object of this class is initialized by setting it to LocationProvider.getInstance(Criteria) , where Criteria is a class that holds the options for the LocationProvider object. 
Examples of the options would be horizontal accuracy, vertical accuracy etc. 
See how these objects are initialized below in the GpsTracker() constructor. startApp() is the entry point for the MIDlet where we create and start a new thread. run() contains the code for the thread, where we call getLocation() of Locationprovider object which returns Location object. 
We then retrieve coordinates from the Location object by calling its getQualifiedCoordinates() method. Once we have the coordinates we can call paintMe() method of MyCanvas to refresh the page.

GpsTracker.java code :

import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.location.Coordinates;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationProvider;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.*;

public class GpsTracker extends MIDlet implements CommandListener,Runnable {
 //Create options menu command
 Command exitCommand = new Command("Exit", Command.EXIT, 2);
 Command refreshCommand = new Command("Refresh", Command.OK, 3);
 Criteria cr= new Criteria();
 Display display;
 Displayable screen;
 LocationProvider lp;
 Location l;
 Coordinates c;
 Thread thread;
 Image image;
 MyCanvas canvas;
 byte[] byte_data;
 String url;
 HttpConnection httpConn = null;
 int respCode;

 
 public GpsTracker()  {
  display = Display.getDisplay(this);
  cr.setHorizontalAccuracy(500);
  
  try {
   lp= LocationProvider.getInstance(cr);
  } catch (LocationException e1) {
   e1.printStackTrace();
  }

  image = null;
  //Add options to menu
  canvas = new MyCanvas(image,0,0);
  canvas.addCommand(exitCommand);
  canvas.addCommand(refreshCommand);
  canvas.setCommandListener(this);
 }

 protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
  lp=null;
 }

 protected void pauseApp() {
 }

 protected void startApp() throws MIDletStateChangeException {  
  try {
   thread = new Thread(this);
   thread.start();
  } catch (Exception e) {
   e.printStackTrace();
  }  
 }
 
 public void exitCom() throws MIDletStateChangeException{
  notifyDestroyed();  
  destroyApp(true);
   }

 public void commandAction(Command command, Displayable d) {
  String label = command.getLabel();
     if(label.equals("Exit")){
       try {
   exitCom();
  } catch (MIDletStateChangeException e) {
   e.printStackTrace();
  }
     }
     
     else if(label.equals("Refresh")){
        refreshMap();
      } 
 }

 public void run() {
  try {
  //get location
  l = lp.getLocation(300);
  if(lp.getState()==LocationProvider.AVAILABLE){
  c = l.getQualifiedCoordinates();
  
  }
  } catch (Exception e) {
   e.printStackTrace();
  } 
  display.setCurrent(canvas);
 }
 
public void refreshMap(){
 try {
    l = lp.getLocation(300);
    if(lp.getState()==LocationProvider.AVAILABLE){
    c = l.getQualifiedCoordinates(); 
    coordinates="";
    image = null;
    canvas.paintMe(image,c.getLatitude(), c.getLongitude()); 
    }  
 }  catch (Exception e) {
  e.printStackTrace();
 } 
}
}

class MyCanvas extends Canvas{
   Image image = null; //the image to be set on the screen
   double lat = 0.0; //latitude
   double lon = 0.0; //longitude

   //constructor
   public MyCanvas(Image m,double lat1,double lon1){
     try{
       paintMe(m,lat1,lon1);
     }catch(Exception e){
       e.printStackTrace();
     }
   }

 //paint the screen
 protected void paint(Graphics g) {
  g.setColor(0xffffff);
     g.fillRect(0, 0, getWidth(), getHeight());

     if(image != null){
       g.drawImage(image, getWidth() / 2, getHeight() / 2, Graphics.HCENTER | Graphics.VCENTER);
       g.setColor(0x000000);
       g.drawString("Lat : " + lat + " Lon : " + lon,getWidth() / 2,getHeight() ,Graphics.HCENTER | Graphics.BASELINE);
     } else {
       g.setColor(0x000000);
    g.drawString("Lat : " + lat + " Lon : " + lon,getWidth() / 2,getHeight() ,Graphics.HCENTER | Graphics.BASELINE);
       g.drawString("GPS Monitor", getWidth() / 2, getHeight() / 2,  
       Graphics.HCENTER | Graphics.BASELINE);
     }
  
 }
 
 public void paintMe(Image m, double lat2, double lon2){
  this.image=m;
  this.lat=lat2;
  this.lon=lon2;
  repaint();
 }
}

Adding Google Maps to the Application With one more simple step google map can be displayed on the screen showing your current location. For that you need this GoogleMaps.java file, download it and include it in your project. Next you need to create an object of type GoogleMaps in you MIDlet, and you can call its retrieveStaticImage(height,width,latitude,longitude,zoom_level,image_format) method which will return the map image.

GoogleMaps map;
 Image image;
 image = map.retrieveStaticImage(480, 320, c.getLatitude(), c.getLongitude(), 14, "png");
 canvas.paintMe(image,c.getLatitude(), c.getLongitude());-->
You can pass this image to paintMe() to draw it on the screen. If you want to display additional details like marker, path etc on the map, modify GoogleMaps.java and modify the return url in getMapUrl() method.

Saturday, September 18, 2010

Html revisited, with WRT Applications

WRT (Web RunTime) is a powerful platform for developing applications for your nokia cellphones without compromising the simplicity of programing. It takes the simplicity down to the HTML level! yes, if you know to develop a web page you can also build an application with the same skills and efforts. You can see the power of html today -> wonderful interfaces could be build using Html/Css and robust functionalities can be given using Javascript. WRT applications or widgets contain all these three components, and these applications run on nokia S60 3rd edition and above. Lets create a small WRT application, a Tic Tac Toe game using html,css and standard javascript library. If you wish to add device dependent functionalities like using the camera etc, you have to include additional javascript library provided by nokia. A WRT installation package has '.wgz' extension and includes five files. First decide a name for your application and create a folder with same name. Then open your favorite editor and create four files in that folder. 
1)A html file, can be named anything (index.html in my case). 
2)A css file with name of your choice (style.css in my case). 
3)A Javascript file with name of your choice (jscript.js in mycase). 
4)A Plist file named info.plist where you save the application information. 
If you need an icon for your application create one and name it icon.png or with whatever extension  

The index.html code :

<html>
<head>
<title>Tic Tac Toe</title>
<script language="javascript" type="text/javascript" src="jscript.js"></script>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div id="row1"><button id="1" onclick="change(this)">?</button><button id="2" onclick="change(this)">?</button><button id="3" onclick="change(this)">?</button></div>
<div id="row2"><button id="4" onclick="change(this)">?</button><button id="5" onclick="change(this)">?</button><button id="6" onclick="change(this)">?</button></div>
<div id="row3"><button id="7" onclick="change(this)">?</button><button id="8" onclick="change(this)">?</button><button id="9" onclick="change(this)">?</button></div>
<div id="row4"><label id="label">Turn : Player1</label></div>
<button onclick="reset()">Reset</button>
</body>
</html> 
The style.css code :

button{
height:50px;
width:50px;
}
The jscript.js code :

Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
}

var win= new Array(new Array('1','2','3'),new Array('4','5','6'),new Array('7','8','9'),new Array('1','4','7'),new Array('2','5','8'),new Array('3','6','9'),new Array('1','5','9'),new Array('3','5','7'));
var arrx = new Array();
var arro = new Array();
var count=0,xcount=0,ocount=0,won=0;
function change(button){

         if(count%2==0){
   button.innerHTML="X";
          arrx[xcount]=button.id;
          button.disabled=true;
   document.getElementById("label").innerHTML="Turn : Player 2";
          count++;
          xcount++;
          if(xcount>=3){
          for(var i=0;i<8 arro="" arrx.contains="" button.disabled="true;" button.id="" button.innerhtml="O" count="" document.getelementbyid="" else="" i="" if="" innerhtml="Turn : Player 1" label="" ocount="" stop="" win="" won="1;">=3){
              for(var i=0;i<8 array="" arro.contains="" arro="new" arrx="new" code="" count="0;" disabled="false;" document.getelementbyid="" function="" i="" if="" innerhtml="?" label="" ocount="0;" reset="" stop="" win="" won="0;" xcount="0;">
The style.css code :





  DisplayName
  TicTacToe
  Identifier
  in.co.presentsoft.tictactoe
  Version
  1.0
  MainHTML
  index.html
  MiniViewEnabled
  


--> 
Note : MainHTML entry should contain the html file name as is within the 'string' tag, and DisplayName should be same as the application name and folder that you created. The Icon : The application can be tested by opening the html file in a web browser. Creating the installation package : Just add the folder with all these files to a zip archive with same name (application name), next rename the zip file extension to '.wgz' and your package is ready. Download my package here

Sunday, September 12, 2010

Jquery - Bouncing Box ScreenSaver

This tutorial will show you how to build a jquery screen saver for your site. I got this silly idea when i had to create a 'website offline' or 'website under maintenance' screen and show something more than just some lines of text. 
This Screen saver contains a box that bounces back n forth on the walls while simultaneously changing its color.The code is very simple and needs no explanation. Any elements in the html can be easily animated using a simple function in jquery -> animate(). 
You can change most of the properties of an element, and it will apply a smooth transition to these changes. animate() takes following arguments : properties : specify the new properties here. duration : the time stretch for this animation in miliseconds. easing : type of animation. callback : the function to be called when animation completes. animate(properties,duration,easing,callback) 
In properties you specify the new properties of the element, like height, width, background etc. The duration is the time deadline within which the animation should complete. 
The third argument is easing, which is the type of animation desired and includes options like swing (default, gives accelerated effect), linear (constant effect), easeOutBounce (Bouncing effect). 
In callback we can define what we need to do once the animation is over. So the complete function looks like this : $('#div-id').animate({height:100px;width:100px},2000,'linear',function(){}); 

The code

<html>
<head>
<title>Work In Progress</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script>>
<script type="text/javascript">
//By TJ
$(function(){
 var x,y,limitx,limity,color,current=0;
 limitx = $(window).width()-100; //the horizontal limit minus box width
 limity = $(window).height()-100; // the vertical limit minus box height

 function animatetop(){ //bounce the box on upper wall
  if(current==1){animatebottom();return;} //don't allow subsequent bounce on same wall
  x=Math.floor(Math.random()*limitx); //upper wall coordinates
  y=0;
  color = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'; //generate random color, requires jquery ui
  $("#box").animate({top: y,left: x,backgroundColor: color},3000,'linear',function(){});
  current=1;
 }
 
 function animatebottom(){  //bounce the box on lower wall
  if(current==2){animatetop();return;}
  x=Math.floor(Math.random()*limitx);
  y=Math.floor(limity);
  color = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
  $("#box").animate({top: y,left: x,backgroundColor: color},3000,'linear',function(){});
  current=2;
 }

 function animateleft(){  //bounce the box on left wall
  if(current==3){animateright();return;}
  x=0;
  y=Math.floor(Math.random()*limity);
  color = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
  $("#box").animate({top: y,left: x,backgroundColor: color},3000,'linear',function(){});
  current=3;
 }

 function animateright(){  //bounce the box on right wall
  if(current==4){animateleft();return;}
  x=Math.floor(limitx);
  y=Math.floor(Math.random()*limity);
  color = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
  $("#box").animate({top: y,left: x,backgroundColor: color},3000,'linear',function(){});
  current=4;
 }

 function animate(){
  var random_num=Math.floor(Math.random()*4);
  switch(random_num){

   case 0: animatetop();
    setTimeout(animate,3000); // next animation after 3 seconds
    break;
   case 1: animatebottom();
    setTimeout(animate,3000)
    break;
   case 2: animateleft();
    setTimeout(animate,3000)
    break;
   case 3: animateright();
    setTimeout(animate,3000)
    break;
   default: animate();
    break;
  }
 }
 
 animate(); //Starting point
 
}); 
</script>
<style>
body{
   overflow:hidden;
   background:url('test.jpg');
}
#launch-date{
   padding-top:250px;
   font-size:20px;
   text-align:center;
   color:white;
}
#not-available{
   font-size:20px;
   text-align:center;
   color:white;
}
#box {
 width:100;
 height:100;
 background:#dddddd;
 position:absolute;
 z-index:-1000;
}
</style>
</head>
<body>
<div id="box"></div>
<div id="launch-date">Bouncing Box</div>
<div id="not-available">Using JQuery</div>
</body>
</html>
Below are some demos : 

 Bounce Effect :  

 Linear Effect :  

 Magnet Effect :

Friday, September 3, 2010

My first Android app - TicTacToe

As you see the market for android phones is expanding, all the major brands have released devices that run Android platform. Android being open source shows a bright future and has lot of scope for development. Today i tried creating an application on Android 2.2 platform and it is so much fun. To start creating your own apps you need to first download Android SDK (and read installation notes). This has a package manager that lets you download all the platforms you want to work on. You can also integrate it with Eclipse The SDK allows you to create virtual devices (Android Virtual Devices or AVD) on which you can test your app.



The app consists of 2 parts, one is the layout or the UI and second, the functionality. The layout is defined in an xml file. Below is the main.xml file code for my TicTacToe application.




The layout structure is similar to html if you see, you have tables, buttons, labels, textfields at your disposal.

The functionality is defined in java language. Below are the contents of my java file.



onCreate() is a function that is called when app starts so you can mark you entry point there. setContentView() lets you set one of the layouts available. findViewById() is used to map the elements in the xml to objects in java (for eg. buttons).

These two components are integrated in a way that allows cross access to resources.
Download the TicTacToe Android source here and the TicTacToe Android application package here.