Another week means another Android application that I’ve managed to push out
This week its a UK lottery results app which obtains the latest lottery results from the interwebs and displays it all nicely on the users screen. The application will work from Android version 1.6, so theres a good chance your handset will support it considering the current version is 2.2 .
You can download via the Android Market by searching market market://search?q=pname:com.damonsk.lottoresults or if you’re posh and have a barcode scanner
<—-
Following on from last weeks app which was launched to the market. This week comes another app available via the market. At this rate I may have to set up ‘a app a week’ weksite – similar to Jayekai’s A Game A Week website
Doubt I have the time to be able to push one out every week.
Anyway, whats this new app about. To summarise the application listens for incoming messages and compares the text to a set phrase. If this phrase matches, the phone activates is GPS receiver and gets the current latitude and longitude. It then attempts to query eighty-six.co.uk in return it will be provided with a URL in which a user can visit to see the current location of the phone. All of this information is then returned to the number that initially sent the message.
The returned messages is similar to the one below;
The application does not need to be running for it to see the incoming message, therefore all incoming messages will be seen.
There admin side to this application provides a discreet interface, so if your phone is stolen, an application with the name Hawkeye will not cause alarm, compared to a name such as ‘Lost Phone Tracker’. The initial screen also prompts for a password which is set when you use the application for the first time. This provides an extra layer of security whilst preventing unauthorised changes. The admin side appears as below.
If the application is unable to contact eighty-six to obtain a URL, the application will sent the message with just the latitude and longitude so your phone can always be located by other means.
Click here to see an example of the URL sent.
Get it now from the market.
Since the Rightmove app was a non-starter, I’ve decided (in my quest to publish my first ever app for a mobile device) to create something else.
I’m not entirely sure where this app will end, but the initial app will be a simple directory with some advanced features. Using the data I collected last year for Rentopoly.com, the app will allow searching by either entering the name of a university/institue, or using GPS find universities/institues near by.
Rentopoly.com was supposed to be the rightmove but limited to only properties to let to students. Depending on how successful Rentopoly.com is, I may include properties as a major part of this application. Maybe this app is what Rentopoly needs to get it going.
So heres what I’ve done so far….
This is the welcome screen, the first thing a user will see when they launch the application. Its nothing great at the moment just thrown together to test the code.
The idea is, the user can either search by name or use their location. Since searching by name is nothing special, this example shows the application using GPS to get the current latitude and longitude.
Once the coordinates have been obtained, the following screen will be displayed.
The next part above is a nice list of results. This information is downloaded from Rentopoly.com as Json, limited to within 10 miles. An advanced feature that will be added will allow this range to be altered.
So thats what I have so far, nothing special but slowly getting back into the Java/Android thing. Stay tuned for updates.
Quick note to say an updated version of CraigsCrawl is now available – 4.1
Includes fixes to the crawl engine and how the URLs are distributed between the engines. Previous versions somehow got stuck and wouldn’t crawl, this is now fixed.
Also the locations are back when crawling CraigsList.
I’ve recently been looking for something to create for Android, something that would be a challenge and not your usual pointless (iBeer/Flashlight yawn…) application. Being a fan of the Rightmove application for the iPhone (which sadly isn’t available for us Android users) I decided to see if it would be possible to create a version for Android, and it is!
I have (so far) created a total of 11 classes, ranging from displaying a user interface to classes which represent an estate agent branch. A main part of the application which the user will never see are the XML handler classes. These 3 objects parse the XML from Rightmove using the SAXParserFactory (Simple API for XML) object, If you’ve ever used this you will know its not the best way to parse XML (in my opinion) but never mind it works. These 3 objects deal with location lookups, property search results and property details and pass information back to other classes dealing with the user interface.
The user interface is quite simple at this stage, I’ve focused on getting the application to work before making it look pretty. The location lookup facility is fully functioning and will return a list of regions from Rightmove which could match that the user is searching for. The next step is to retrieve the properties for this region and display them to the user. At this stage there are no filters like those appear in the iPhone version but this can be added later.
The last step is when the user selects a property to view, this will create a new view that will be similar to that on the iPhone version. As you will see below it still needs a lot of work.
UPDATE: Please see here
This example will allow a Android application to connect to a web service that serves JSON objects/arrays. This example has been derived from the RESTful example posted here.
This app will connect to a web page/site/service located – http://rentopoly.com/ajax.php?query=Bo and returns a JSONArray of towns/cities and universities that match the supplied query. This service produces the following output;
// {"query":"Bo","suggestions":["Bognor Regis","Bolton","Bournemouth","Camborne","Eastbourne","Loughborough","Peterborough","Scarborough","University of Bolton","Boston University","Bournemouth University","Camborne School of Mines","Loughborough University","Ravensbourne College of Design and Communication","University of Hull (Scarborough Campus)"]}
Now to explain how it all works.
When the application loads it creates the layout and textview component. It then sets the text of the textview by calling connect() function. This function returns a string.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
txt.setText(connect("http://rentopoly.com/ajax.php?query=Bo"));
}
The connect function will accept a string as a url and create a HttpClient object;
private String connect(String url){
// Create the httpclient
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Declare a response
HttpResponse response;
// Declare a return string
String returnString = null;
.....
From the partial code listing above, the function accepts a URL as a string, create the HttpClient (used to fetch the webpage), delcares a HttpResponse (for the response) and String (which will be returned as the result of this function). The HttpResonse will contain the response including headers such as 200 for ok, 301 for redirect and 404 for file not found. In this example we will only focus on the 200 response.
Next part of the connect function is to open the webpage (execute), check the status of the response and check the body contains text.
try {
// Open the webpage.
response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode() == 200){
// Connection was established. Get the content.
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
....
The next part is to convert the InputStream into a string. This uses the convertStreamToString function which was found from the RESTful example noted earlier.
At the same time, the string will be converted into a new JSONObject (jsonResponse). The follwoing code shows how this is done…
// Load the requested page converted to a string into a JSONObject.
JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
// Get the query value'
String query = jsonResponse.getString("query");
// Make array of the suggestions
JSONArray suggestions = jsonResponse.getJSONArray("suggestions");
// Build the return string.
returnString = "Found: " + suggestions.length() + " locations for " + query;
for (int i = 0; i < suggestions.length(); i++) {
returnString += "\n\t" + suggestions.getString(i);
}
// Cose the stream.
instream.close();
....
The above code has create the JSONObject from the string. Now to make this object into somethnig meaning full that can be returned. The first step creates a String named query which will contain the string named “query” from within the JSONObject. In this case this would be “Bo”.
The next step is to get the available suggestions in the object and convert them into a new Array. This is done by calling the getJSONArray() method suplying the “suggestions” as the key.
Now we have an array, its a simple case of looping through and making a nice string.
The last part is to close the inputstream by calling the close() method to free up resources and return the string created. There are a couple of catch blocks which will catch exceptions raised by the JSONObject or HttpClient.
}
}
else {
// code here for a response othet than 200. A response 200 means the webpage was ok
// Other codes include 404 - not found, 301 - redirect etc...
// Display the response line.
returnString = "Unable to load page - " + response.getStatusLine();
}
}
catch (IOException ex) {
// thrown by line 80 - getContent();
// Connection was not established
returnString = "Connection failed; " + ex.getMessage();
}
catch (JSONException ex){
// JSON errors
returnString = "JSON failed; " + ex.getMessage();
}
return returnString;
}
The complete class source code follows;
/**
* Modified example taken from
* http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
*
* This class will connect to a website, get a JSON Object and display results into a textview.
* @author Damon Skelhorn - eighty-six.co.uk
*/
package com.damon86.httpdownload;
import java.io.InputStream;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Httpdwld extends Activity {
/** Called when the activity is first created. */
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
txt.setText(connect("http://rentopoly.com/ajax.php?query=Bo"));
}
private String connect(String url){
// Create the httpclient
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
// return string
String returnString = null;
try {
// Open the webpage.
response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode() == 200){
// Connection was established. Get the content.
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
// Load the requested page converted to a string into a JSONObject.
JSONObject myAwway = new JSONObject(convertStreamToString(instream));
// Get the query value'
String query = myAwway.getString("query");
// Make array of the suggestions
JSONArray suggestions = myAwway.getJSONArray("suggestions");
// Build the return string.
returnString = "Found: " + suggestions.length() + " locations for " + query;
for (int i = 0; i < suggestions.length(); i++) {
returnString += "\n\t" + suggestions.getString(i);
}
// Cose the stream.
instream.close();
}
}
else {
// code here for a response othet than 200. A response 200 means the webpage was ok
// Other codes include 404 - not found, 301 - redirect etc...
// Display the response line.
returnString = "Unable to load page - " + response.getStatusLine();
}
}
catch (IOException ex) {
// thrown by line 80 - getContent();
// Connection was not established
returnString = "Connection failed; " + ex.getMessage();
}
catch (JSONException ex){
// JSON errors
returnString = "JSON failed; " + ex.getMessage();
}
return returnString;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
To celebrate my new purchase for a Google Nexus One – I’ve started looking into Android development.
Android is built in Java and since I studied Java at University I decided to have a little play. From experience of using Android there are times when on screen messages pop up for whatever reason. In Android these are called Toast.
I’ve included a full class which explains how these Toast Objects are created. If you’re just interested in getting a Toast message to appear then the following code will work for you.
// Create a piece of toast. Toast pieceToast = Toast.makeText(getApplicationContext(), toastText.getText(), Toast.LENGTH_SHORT); // Show the toast. pieceToast.show();
The following class is a complete application albeit a very small one. Its purpose is to display a text field which allows the user to enter text and button which will show a Toast message.
/** * This is a Android example to which shows how to display a piece of toast. * Makes use of OnClickListener interface * * @author Damon Skelhorn*/ package com.damon86.toastExample; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; public class ToastExample extends Activity implements OnClickListener { /** Called when the activity is first created. */ // The text and button used on the display. EditText toastText = null; Button showToast = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create a new Layout. LinearLayout rootLayout = new LinearLayout(getApplicationContext()); // Create textfield toastText = new EditText(getApplicationContext()); toastText.setText("Hello Toast!"); // Create button and set OnClickListener showToast = new Button(getApplicationContext()); showToast.setText("Show Toast"); showToast.setOnClickListener(this); // Add components to the Layout. rootLayout.addView(toastText); rootLayout.addView(showToast); // Add the layout as the content view for the application. setContentView(rootLayout); } /** * Implemented method - onClick. * Show the user a piece of toast. */ @Override public void onClick(View v) { // Create a piece of toast. Toast pieceToast = Toast.makeText(getApplicationContext(), toastText.getText(), Toast.LENGTH_SHORT); // Show the toast. pieceToast.show(); } }
The class implements the OnClickListener Interface. For those who do not know what an interface is, its a absract type which contains a set of empty methods know as method signatures. When a class implements a interface, Java expects your class to contain these methods. You can then write any code within these methods.
To make sure the button executes the code contained in the onClick method, the onClickListener is set on the button by using the following code;
showToast.setOnClickListener(this);
Java is still fairly new to me, I have about 4 months exposure to it.
One thing that I like about the developer community is that there are various sources that can explain how to do something in anything. I often finding myself reading someones blog whilst trying to figure something out. So I’m returning the favour.
In this post, I will attempt (apologies if it sucks) to explain as much as I can on how to use the ArrayList in Java. I’m sure you are aware what an ArrayList is, but if not heres a quick explanation. A ArrayList is a one dimension array/stack which can contain Objects, it’s size (amount of objects it can contain) is not set but grows automatically. The size of the ArrayList can be set when you instantiate by using ArrayList(100). The ArrayList functions allow you to;
- add(Object o) — Allows you to add objects.
- get(int objectIndex) — Get an object using its index
- size() — Get the size of the ArrayList.
- remove(int objectIndex) — Remove an object from the ArrayList from the specified index.
- indexOf(Object o) — Get the index of an Object.
- clear() — Remove all objects from the ArrayList.
How to create an ArrayList
Here is an example taken from a recent uni assignment. Lets say I sell Cars and in the application there is a Class called Car which represents a car that I may have. Here is how we would populate an ArrayList with Car objects.
ArrayList carStock = new ArrayList<Car>;
Car toyotaYaris = new Car("MF54 XLL", "Petrol", "Blue", "Hatchback", 3500.0f);
carStock.add(toyotaYaris);
From the above example, you can see I created a new ArrayList called carStock. This ArrayList will contain Car objects which is defined by <Car>. The next step is to create a Car object which represents a Toyota Yaris, registration number: MF54 XLL, colour: Blue, fuel: Petrol and Costs £3,500.00. Once this is created, the Object is then added to the ArrayList by calling the add() method.
Searching ArrayLists
Continuing on the Car example, this example will show how to get a Car out of the ArrayList using Iterator and the cars registration number. This will be made into a function called getCar. This function will return a Car object.
public function Car getCar(String registrationNumber){
for (Iterator<Car> i = carStock.iterator(); i.hasNext();) {
Car currentCar = (Car) i.next();
if (currentCar.getRegNumber().equals(registrationNumber)) {
return currentCar;
}
}
return null;
}
This method takes a string represented by registrationNumber and will loop through the carStock ArrayList checking each time if the registration of the current car is equal to the one provided. If the car matches, it will return the Car object.
The for loop shown above checks each cycle if the carStock iterator has another object using the hasNext() method. This method will return a Boolean (true/false) value each cycle. As long as the Boolean value is true, it will continue to cycle through the ArrayList.
So we have a new function, how do we use it? Assuming somewhere else within the application we want to search for a car, the following code would be used;
Car foundCar = getCar("MF54 XLL");
system.out.println(foundCar.getRegistrationNumber());
This code will call the new method getCar() with the registration number “MF54 XLL” and set the object reference of foundCar to that contained in the ArrayList (carStock). That reference traces back to toyotaYaris.
The getRegistrationNumber() would be a method within the Car Class and shown as an example.
I hope this was useful, please feel free to leave comments.
My first semester back at University is almost complete, only two assignments (both completed) to hand in and then I’m done! This semester has been quite easy, I’ve had to do 6 assignments in total, 4 in Java and 2 in .Net. All the projects have been to create some kind of application, be it for a company who’s employee hierarchy resembles a pyramid scheme but overall nothing too hard. At the end of it all, I can say I know Java, which opens the way for some Android development when the GooglePhone/Nexus One comes to the UK.
A couple of posts back I said I would learn C++ whilst learning Java. I can honestly say this never happened, however I don’t see learning the language a challenge anymore. One day I will finally get to program something in this language but I wont be going out of my way to do something in it.
A new year has forced me to get back into a exercise regime again. So far I’ve been good and eventually I might be able to report some losses or gains. My goal at the moment is to try and stay the same weight but lose some fat in exchange for muscle.
Onto work… The new year saw me working from home for the first time thanks to the weather (constant snow since Christmas). A very different experience compared to working in a office (how do people work from home?) I will not miss it. We have started a couple of new projects, both based in PHP using SOAP connected to a MySQL database, Good fun!. Negotiated a pay rise over MSN
and a bag of holidays left to take.
Thats it for now.
Ok so blogging isn’t really up there with my priorities. This just means I write more less often.
My semester at Uni is nearly over, only a couple of weeks left followed by a short break and i’ll be starting the next semester. The most interesting thing i’ve learned so far this year Object Orientatation. When I started my job at 3DPixel.net my first project was using PHP and OO techniques and I can honestly say I didn’t understand most of it at first but now it all makes sense.
I’ve started on a new personal project (http://rentopoly.com) to pass the time (when I have free time) which is a website targetted at students and landlords looking to rent properties. I will be using my new found knowledge of OO to build the website.
I have so far created one object which I think could be interesting for other people to use. This object connects to Yahoo! MapService API to resolve an address (via Curl) into geo latitude and longitude data. This is usefull if you need addressing lookup without having to purchase data like that supplied by the Post Office (PAF File).
To use the object;
$myAddress = new Address("House and Street Name", "Locality", "City Town", "Postcode");
echo $myAddress->getLatitude();
echo $myAddress->getLongitude();
/* You could also use the object to display address information */
echo $myAddress->getAddress1();
echo $myAddres->getCity();
You can use this with GoogleMaps to place a marker on a map.
Full object source.
/*
* Creates an address object
* See - http://eighty-six.co.uk/blog/2009/12/oo-techniques/
* @author Damon Skelhorn
*/
class Address {
private $postcode;
private $address1;
private $address2;
private $city;
private $longitude;
private $latitude;
private $url = "http://local.yahooapis.com/MapsService/V1/geocode?appid=yourapikey";
function __construct($address1, $address2, $city, $postcode){
$this->setAddress1($address1);
$this->setAddress2($address2);
$this->setCity($city);
$this->setPostcode($postcode);
$this->resolveAddress();
}
private function resolveAddress() {
$stream = "location=" . $this->getAddress1() . ",".$this->getCity() . "," . $this->getPostcode() . '&output=php';
$res = $this->fetchPage($this->getUrl(), TRUE, $stream, '');
$res = unserialize($res);
$this->setLongitude($res['ResultSet']['Result']['Longitude']);
$this->setLatitude($res['ResultSet']['Result']['Latitude']);
}
private function fetchPage($url, $ispost, $params, $auth){
if(!$ispost && $params) $url .= '?' . $params; //if not post and params (ie, if it's a get)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if(is_array($auth)){
curl_setopt($ch, CURLOPT_USERPWD, $auth['username'] . ':' . $auth['password']);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
}
if($ispost){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function getAddress1() {
return $this->address1;
}
private function setAddress1($address1) {
$this->address1 = $address1;
}
public function getAddress2() {
return $this->address2;
}
private function setAddress2($address2) {
$this->address2 = $address2;
}
public function getCity() {
return $this->city;
}
private function setCity($city) {
$this->city = $city;
}
public function getPostcode() {
return $this->postcode;
}
private function setPostcode($postcode) {
$this->postcode = $postcode;
}
private function getUrl() {
return $this->url;
}
private function setUrl($url) {
$this->url = $url;
}
public function getLatitude() {
return $this->latitude;
}
private function setLatitude($latitude) {
$this->latitude = $latitude;
}
public function getLongitude() {
return $this->longitude;
}
private function setLongitude($longitude) {
$this->longitude = $longitude;
}
}
?>











