Tube Delay Refund for android released

14/07/2010

Update (v1.4.0) National Rail & TFL Travelcard support has been added. (August 2nd)

Update (v1.3.2) Some layout rejigging has been done, defaults added and a few more menu options for resetting/prefilling. The preferences layout has also been tidied. (July 17)

Updated (v1.2.0) I have updated this app to disable submission until all the station/date info is added. I’ve also added some more labels to show what’s been entered so far. You must make sure you’ve filled in all the preferences or else it’ll fail (Click menu>preferences). (July 16)

A few days ago I was in bed trying to sleep and I suddenly thought it would be good if there was an app to submit refunds for the tube as you come out. I had in my head the idea of a timer that would count down from 15 minutes and then alert you that you were in valid refund territory.

After I coded said timer, I pushed it live without refund submissions working. I also did a quick google to see what else there was only to discover that there was a company that released the exact same app on the iPhone about 3 months ago. Let this be a lesson that if you are about to code something as an exercise don’t go googling first or you’ll inevitably be put off because “whats the point”.

Several hours later today and it is now submitting refund applications to TFL and I get an email confirmation with the reference number. I’m very happy if incredibly tired. The app is free for now, all the others that do these on Blackberry/iOS are paid for. There doesn’t seem to be one for android yet, the guys that did the iPhone app said they where working on one way back in March or April, not quite sure what happened to it. They’re about to release the blackberry one so for now this is the only refund submission app on android :D Took me basically 2 days part time.

From a technical point of view this is making use of the apache http libraries to do a GET request for the TFL refund page. It parses that to grab the ASPX Viewstate variable and session cookies. Then it grabs the data from the main activity and combines that with the data stored in shared preferences for the form variables. The POST request is processed and the response parsed again to find the reference number. That’s then displayed via a Toast call. Fairly simple, having to deal with the viewstate crap was probably the most annoying part, that and debugging the actual POST.

4 Comments

SpineMagazine.com radio player & news reader for android

2/07/2010

Quite a while back I was trying to get my head around the fairly complex ListView control for android and something I thought perfect for it was the set of radio shows over at spine magazine.

I have had this code sitting around for a while and I thought why not knock out the news code and release it and then just continue to work on it and update it. As the saying goes, release early, release often! I think it’ll be easy enough to add in reviews using the same sort of code to get the data and just re-using the show layout. This particular app was a lot more complicated than the django-reference thing, so here is some of what I’ve learned… You can get this in the marketplace now. Bug reports are expected & indeed welcome.

Warning! Technical crap follows.

It takes a bit of time to get your head around it, essentially you subclass the ArrayAdapter class with a container class to hold your list view elements. The ArrayAdapter is a templated class so you first need another class that is actually going to hold your data. This is were you’ll need to create a class for your data and then instantiate the ArrayList with this type. The code to hold my news post data is very simple:

package eu.jaymz.spinemag;
 
import android.util.Log;
 
public class NewsPost {
    private String title;
    private String description;
    private String date;
    private String author;
 
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
 
}

Then in my main activity class I cast the templated ArrayList to a NewsPost class:

ArrayList<NewsPost> spr_news = new ArrayList<NewsPost>();

With the data structure sorted I need a method in my ListView activity to actually fill in the ArrayList with data. This is very typically something along the lines of the following, here I read the JSON data from a URL, decode it and assign it to the class members, finally appending it to the ArrayList from earlier.

private void getPosts() {
        try {
            URL url = new URL("url for data");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str = in.readLine();
            in.close();
            spr_news = new ArrayList<NewsPost>();
            JSONObject json = new JSONObject(str);
            JSONArray posts = json.getJSONArray("posts");
            for(int x=0; x < posts.length(); x++) {
                JSONObject post_data = new JSONObject(posts.get(x).toString());
                NewsPost post = new NewsPost();
                post.setTitle(post_data.get("title").toString());
                post.setDescription(post_data.get("description").toString());
                post.setDate(post_data.get("date").toString());
                post.setAuthor(post_data.get("author").toString());
                spr_news.add(post);
                //Log.d("NEW", "added a post - "+post.getTitle());
            }
        } catch (Exception e) {
 
        }
        runOnUiThread(setPosts);
    }

With all the above in place the code is at the point where there is now an array full of structured data for our ArrayAdapter to show. To do this the ArrayAdapter needs subclassed to work with our earlier NewsPost classes members:

private class NewsAdapter extends ArrayAdapter<NewsPost> {
 
        private ArrayList<NewsPost> items;
 
        public NewsAdapter(Context context, int textViewResourceId, ArrayList<NewsPost> items) {
                super(context, textViewResourceId, items);
                this.items = items;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.post, null);
                }
                NewsPost o = items.get(position);
                if (o != null) {
                    /* hmm, this looks proper ugly */
                    TextView title = (TextView)v.findViewById(R.id.post_title);
                    TextView description = (TextView)v.findViewById(R.id.post_description);
                    TextView date = (TextView)v.findViewById(R.id.post_date);
                    TextView author = (TextView)v.findViewById(R.id.post_author);
 
                    description.setText(o.getDescription());
                    title.setText(o.getTitle());
                    author.setText(o.getAuthor());
                    date.setText(o.getDate());
                }
                return v;
        }
    }

All this code is really doing is loading the layout resource XML for our row and binding the data from the array elements members to views within the XML. Finally we need to tell the list view to update. Typically the above code has all been kicked off and ran in a thread, populating the ListView when it’s actually finished without stalling the phone itself.

for(int i=0;i<spr_news.size();i++) {
    n_adapter.add(spr_news.get(i));
}
m_ProgressDialog.dismiss();
n_adapter.notifyDataSetChanged();

All the above is doing is updating the ArrayAdapter and adding our ArrayList elements to display. We then signal that the data has changed which will cause the ListView itself to update. Simple! :) Again, I must make the point of how verbose this all feels when I’m coding in python all day. I’m sure it needs a good refactor to now but I’m a lot more familiar with the way android works with layouts and indeed strong typing :)

1 Comment

Using stochastic processes to generate paint type effects in processing.org

15/06/2010
I very much like to play with processing.org when I’ve got some downtime. I’ve wrote a small particle engine a while back in the framework and this time I thought I’d try and do something a little more arty from the outset. My inspiration for this “sketch” was the many splatter paintings by Jackson Pollock. I can remember going to see some of his work at the Tate modern in London quite a long time ago. I had always thought it a bit poor as “art” when I was a kid but later on I developed an appreciation for the format. If you have no idea what I’m talking about, this is an example:
Now my sketches don’t look much like this but I did capture some of that splattering chaotic effect that I wanted. The basic process is very simple, a class called a Walker will randomly make its way across the canvas. As it moves the vector distance of each step is calculated. If the step is big enough it causes a burst of circles to be drawn, each with a slightly random position & varied alpha to give it some texture. To avoid it becoming a little too busy I’ve limited it to a set palette at runtime which can be regenerated as walkers are added.

I was quite happy with the random scatter effect as different pools of colour made their way through the canvas space. I thought it would be a nice addition to add in some basic boundary conditions so I added a quick polygon class and added in an array of those. A few functions later and I could click around the screen defining new polygons. Using the well known Jordan Curve theorem we can tell if the walker is currently within an arbitrary polygon (without holes of course). Here’s an example video of it in action. Heart’s seem pretty easy to draw compared to anything crazy complex and give a good idea of the effect:

I’ve added quite a few options to the code now allowing me to switch on & off the boundaries as well as add an arbitrary number of polygons. If the vertices overlap then the way the “point in polygon” algorithm works it will flag each “contained” area as a solid.
Finally here is a nicely captured heart shape. It gives a nice idea of the kind of effect when combined with a boundary. I think playing around with the way the walkers are coded could be fun, for example doing a neighbour check and tweaking the randomised movement accordingly could create a weak flocking style system with Brownian motion driving it.
If you’re interested in checking the code out you can find it over on github. It should run for you ok out of the box within your processing environment.
No Comments

Django Reference in android market now

28/05/2010

Very late last night, as I was enjoying “The Design & Evolution of C++” (an excellent book, even if you’re not a C++ dev), I took a short break and was browsing around on the android market place and noticed there was no django app. I’ve recently picked up an HTC desire and have been really enjoying developing on it. I’m currently working on an application for Crooked Tongues to allow people to post & comment their sneakers (don’t ask…) and I thought this would be a quick app to do and get out there. Anyone starting out developing apps will be aware that one of the hardest things is just thinking of something that isn’t already crowded out by what’s already available.

Basically, all I wanted was a more dedicated browser for the django docs. The content there is excellent so I quickly knocked together an application that lets you jump to major sections, set a page zoom by default and switch version easily. All in all it only took a few hours of development and thanks to the approval procedure it’s already available to install.

It’s a glorified web view but it’s a start point and its at least out there now. I’m getting a lot more used to the dev process now on android. The total code for this app weighs in around 400 lines – around 80 of those being XML to define the layout and strings used. The main activity class then manipulates the XML defined webview component to react to the (again XML) menu. My main constructor method looks like this:

@Override
    public void onCreate(Bundle savedInstanceState) {
        Resources res = getResources();
 
        version = res.getString(R.string.default_version);
        base_url = res.getString(R.string.url_base);
 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        webview = (WebView) findViewById(R.id.webview);
 
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebViewClient(new DjangoWebClient());
 
        final View zc = webview.getZoomControls();
        FrameLayout mContentView = (FrameLayout) getWindow().getDecorView().findViewById(android.R.id.content);
        mContentView.addView(zc, ZOOM_PARAMS);
        zc.setVisibility(View.GONE);
 
        setZoom();
        loadDocs();
    }

The remainder of the methods are basically just reacting to the menu choices and directing the webview url appropriately. All in all quite simple.

No Comments

Crooked Tongues TIA android app – Week 1

16/05/2010

I recently picked up an HTC desire and have been loving android as a platform. I’m not entirely sure why I didn’t go for android to begin with (apart from doing my friend Spangsberg a favour by buying out his iPhone contract before he left the country). I dabbled a little with objective C but not owning a full on mac for dev’ing put me off spending a significant time at home coding for the device. That and it seemed like a lot of work to get going (probably because I use Linux almost all day so am not used to the Mac toolchain).

Working with android on linux has been a total pleasure. Mostly. I’m still getting re-used to the verbosity of java compared to my day-to-day python but the experiance has been a good one so far. I’ve basically been learning by looking at the sample apps supplied combined with a lot of googling and reading of android dev forums. There is a real wealth of documentation out there and there’s an absolute ton of general java code to solve most problems. This is where I’m at about a week into it (spending a couple of hours every few days on it).

The HTTP posts are working now as is uploading a camera shot, you can store user/passwords and then it’ll do the form posts with that data. For now I have it just “logging” in to a dummy setup on my own server – that side is just some PHP for now. The real backend runs python (django), for now its just easier to run that data through some PHP on my blog server. The data for the views comes via a JSON array, that data is served up via python and is essentially just a REST interface to the TIA area. I’m mainly concentrating on just learning my way around the SDK but already I’m seeing that theres a lot of power in combining the android platform with django (and maybe django-pistons on top) to create rather powerful connected mobile apps.

2 Comments

Beginnings of a particle system in processing

1/02/2010

I have been getting more & more into processing and who doesn’t love particles? I’ve started the basis of a little particle system, there are plenty of examples at openprocessing.org but I wanted to write my own as an exercise. It’s been quite some time since I properly used even pretty basic maths for physics so I’ve been enjoying revisting old uni notes & following through my old engineering books.

I have it colliding in a rough way with the walls. There’s no horizontal component to forces yet, it just drifts as time increases rather than falling straight down. It goes crazy as I’m changing the “gravity” throughout. Hopefully this will continue to grow as I add bits and (re)learn the concepts. So far this probably about 100-150 lines of code, not a lot.

No Comments

Old school demo effects: #1 – the plasma

31/01/2010

I have finally gotten around to playing with processing – a java based set of libraries and functions for visual programming. It’s really a lot of fun. It’s great for doing quick and easy interactive visualizations. With minimum code you can start drawing simple geometric shapes and when you start throwing around a few sine curves and mouse co-ordinates you’d be surprised what can come out.

One thing I’ve always promised myself I’d code was a plasma effect. A stalwart of the 8-bit demoscene I’m not sure why it’s taken so long for me to get round to actually coding one from scratch. As you can guess, processing made it pretty straightforward. Here’s the result:

This plasma harks back to one of the first group assignments I had at university where we were given an FPGA and we had to load in a picture of Lena and do something with it. The plasma never materialised, instead we ended up doing a convolution kernel. I can remember we had around 2 weeks to do it (teams of 4 or 5) and write a little report. I wrote this in the space of an hour or two.

If you’ve never used it before and have always wanted to do a bit of abstract graphical programming I’d highly recommend it. The core keywords/methods are all pretty sensible and once you’ve worked through a few basic “sketches” the whole thing begins to gel easily and you start thinking less about the code and more about what you want to do on screen.

Here are a few images I’ve created via scanning each sampled point and matching it with others in the image within a threshold. A bezier line then connects the points.

No Comments