Archive for the ‘Android’ Category

UK Property Market – The rightmove for Android!

Thursday, July 15th, 2010

If you have followed my blog, a couple of months ago I started to develop a Rightmove app for Android.  I got to the stage where I felt I should seek permission to release the app using the data supplied from Rightmove before I continued.  Unfortunately they refused.

Never mind..

A few week ago I started to look for a new data source that provides property data to be included in the application.  I found that data from Google.

Over the past few days I’ve been working to get the application to a preview state where I feel it’s buggy  stable enough to use.   The application is now available to download via the Android Market.

Here are a couple of images showing the application in use.

Search Results

Search

And a promo image;

Promotion

Future plans include social sharing via email, twitter etc from within the application and also launch a website that can assist with displaying the properties to non android users.

Download

Use a QR code scanner

QR Code

Manually install from the Android Market

  1. Go to ‘Market’ on your Android-powered device.
  2. Select ‘Search’.
  3. Enter ‘UK Property Market’ into the search field.
  4. Once you’ve found the ‘UK Property Market’ app, touch to install.
  5. Follow the onscreen instructions to proceed with the installation.

UK Lotto/Lottery Results (Week 3)

Monday, June 14th, 2010

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

<—-

Hawkeye – New Android App (Week 2)

Saturday, June 5th, 2010

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.

UK Universities – Android App (Week 1)

Saturday, May 29th, 2010

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….

Initial Screen

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.

Results

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.

Rightmove – The Android Application

Wednesday, February 10th, 2010

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

Parse JSONArray + JSONObject from webpage/website using HttpClient

Sunday, January 24th, 2010

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();
    }
}

JSON HttpClient Example

Android OnClickListener and Toast Example

Monday, January 18th, 2010

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);

Download complete ToastExample Project

Screenshot