Archive for the ‘Java’ 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

Java ArrayList and Iterator

Thursday, January 14th, 2010

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.

Checking in…

Thursday, January 14th, 2010

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.

Back to University – A New Language++

Sunday, September 6th, 2009

I’ve recently got hold of my timetable for this years first semester at University and I’m quite excited!¬† My first year at uni was great, I really enjoyed everything I did except one subject which I felt was completely unrelated to what I was studying.¬† Anyway..¬† this year I will be studying Java along with more VB.Net and programming and design.¬† I have two lecturers which I had last year which is good as I enjoyed their classes.

Java has been something I have never really looked at in great detail, actually – in any detail at all so learning a new language is quite exciting.¬† Whilst studying Java and VB.Net at University, I will also start to study C++ in my own time.¬† I’ve always wanted to learn C++ however its syntax has always put me off in the past.¬† But with my new found experience with C languages (mainly Perl and PHP) which I have gained from working at 3DPixel.Net I’ve made the commitment to learn this language once and for all –
cout << “the basics anyway\n”;

In the past, I’ve only ever concentrated my time using a single language – this being VB.Net for any type of project.¬† Don’t get me wrong, I like using VB.Net simply because its quick and easy to use, however, is there really a demand for a VB.Net developer in the industry?¬† Surely a programmer that can write in a C language is sought after more? Not to mention the difference in salary.

I’ve recently forced myself away from using VB.Net with the exception of the program I am currently developing at my job and trying to use other languages instead of using VB.Net for anything that I feel the need to program.¬† Working at 3DPixel has helped me do this with project such as CheckMyBox.Net which was created in Perl (the backend anyway).

I’ve used VB since I was around 13, starting out by creating various chat bot programs for AOL, thats almost 10 years of using VB. Most recently (the past 3 years) I made the jump to VB.Net. This istelf was quite a challenge at the time considering I almost gave up on the idea of programming as a career after I left college.

Hopefully, I will pick up Java and C++ without any problems as I did with PHP and Perl.¬† If all goes well, I think Objective-C is next on the plate, but (for now) I’m not saying goodbye to VB.