Programming and general geekiness.

Posts tagged ‘programming’

Moving content over to Programming Thomas blog

I’ve decided to move the majority of my content over to my Programming Thomas blog instead of this one because it fits better with my other projects. Please go over there for any updates to my apps and general programming information.

Programming Thomas on


Things I’d like from Android

Android is a good platform – not a great platform, but a good one. I’ve been doing a lot of Android development recently and it certainly has many good features and it is easy (and cheap) to make an app for the system. There are, however, a great number of problems with Android from a developer’s point of view. This is a rough list of things I would like to see from the Android project. I don’t think that it necessarily needs them, but I think it would be a good thing for the platform if it had a few of them:

  • SVG support everywhere: A major problem with Android at the moment is that you have to create at least three different copies of the same icon for use in app because Android apps can run on many different devices at different resolutions. If all icons were changed to SVG it would be possible to just include one copy of the icon and know that it would be shown at maximum quality on all screens. This would also be useful when Android displays eventually get to a higher pixel density (as in the iPhone and iPad) as icons would never appear pixelated. SVG font support would also be handy but not a requirement.
  • Better font support: Android currently comes with three fonts whereas Windows Phone and iOS come with over fifty. You can include fonts in your app however if you wish to do this you have to change the font of each View pragmatically rather than via styling or XML which can increase the size of the app and also make it slower. Again, SVG font support would be useful.
  • Higher PPI displays: When the iPhone got a Retina Display the only way that Android devices could get a similar resolution was to get bigger screens because Android wouldn’t run as well on higher density displays. There should be some big system changes to get this support.
  • One Android: It amazes me how phone manufacturers have fragmented Android by adding new UIs and alternative apps. Whilst some of these are really great it often means that some devices won’t receive a major update for months after it has been released because the UI is being developed. If Android could go back to being pure Android it would make it a lot easier for developers and require less testing of apps.
  • Google Play gift cards: This seems like a painfully simple thing to do but it is one of many reasons why iOS developers make a lot more than Android developers. It is a well known fact Android users ‘don’t like buying apps’ however the problem is that most of them can’t. When you set up an iTunes account you either have to type in your bank details or set it so that you will use gift cards however this is not required for Google Play registration. As most Android users have not created a Google Wallet account they can’t buy Android apps. By selling gift cards everywhere (as iTunes does) more people are likely to start buying apps.
  • Better integration between Eclipse and Google Play: Currently you can create an app in Eclipse, export it and then upload it to Google Play. It makes a lot more sense, however, to integrate the two so that developers sign into Eclipse and then press one button to upload an app to Google Play. This would also simplify the process of creating in-app purchases.
  • OTA updates: Most iOS devices are now running iOS 5.x and many are already running iOS 5.1, which came out in the last month. On Android most devices are still stuck with a two year old version of Android because phone manufacturers (who are responsible for updates) have not chosen to update to Ice Cream Sandwich. If Google were to take over the updating of Android devices it would probably mean that more people were using the latest version of the software.
  • Better emulator: The Android emulator is very good however it can be incredibly slow when trying to emulate Android 3.x and Android 4.x devices.

Sharing and saving Bitmaps in Android

If you’ve ever worked with Android development before you’ll probably know that once you get it right it can be incredibly rewarding however if you get it wrong it can be a real pain to fix. Sometimes the development also demonstrates the fragmentation of Android and how it can be a great challenge to do something relatively simple because it works differently on different devices.

I recently developed the Keep Calm app for Android that allows users to create Keep Calm and Carry On style posters. The app has been a reasonable success (20,000 downloads in a month) however there has been one major issue: not everyone could save properly. At first I didn’t really understand why this was because all of the testing I had done indicated that the Bitmap object that the image was stored in was being correctly saved to the SD card and it would then appear in the Gallery app. However, this was not the case for everyone.

I soon discovered that it wasn’t a technical issue with my app entirely. The default Gallery app gets a list of files in the various images folders on the SD card each time it loads but the Android system doesn’t always refresh this list of files very often – sometimes only when the device is restarted. Clearly it would have been a major issue for my users to have to restart their phone each time they wanted to view a file so I came up with this solution:

String saved = Images.Media.insertImage(this.getContentResolver(), bitmap, title, description);
Uri sdCardUri = Uri.parse("file://" + Environment.getExternalStorageDirectory());
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, sdCardUri));

The bitmap object is of type Bitmap whereas title and description are both Strings. The sendBroadcast function (your activity inherit it as the class extends Activity, where the function is) then forces the OS to remount the SD card as it would do when the device starts up meaning that your picture will appear in the Gallery app. If you want to prove this to your users you can load up the file in the app:

Intent intent = new Intent();
intent.setDataAndType(Uri.parse(saved), "image/*");

This then loads the image up, using an Intent, in whatever the default Gallery app is. Remember that you’ll need to add the android.permission.WRITE_EXTERNAL_STORAGE to your Android Manifest otherwise the app will fail. The obvious progression of saving is, of course, sharing and Android makes this incredibly easy to do without having to use the APIs of all the various social networks that exist – instead the app can just utilize services provided by other social network apps on the phone. Here is how to do it:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(saved));
startActivity(Intent.createChooser(sharingIntent, "Share image"));

This loads up a menu (unless no options are available other than email) headed with the “Share image” text asking the user what service they would like to share it with. The appropriate app will then launch. Another cool thing I’ve done using a Bitmap is to set the wallpaper. You’ll need to ensure that the Bitmap is double the width of the user’s device and the same height (explained in this Lifehacker article) – this could be done using a Canvas. Here is the code you can use:

WallpaperManager wallpaperM = WallpaperManager.getInstance(this);

Like with saving, you’ll need to ensure that you add the android.permission.SET_WALLPAPER t0 your manifest otherwise, again, the app will fail. Hopefully this article has helped you with your projects and if you have any other problems leave me a message in the comments.

Prerequisites for Android Development

I really like doing Android development and over the past few months I’ve done quite a bit of it but I found at the beginning that some things didn’t seem to be entirely logical that were quite important despite the fact that I already had a vast programming knowledge. Here is a list of things I reckon are useful for learning Android development:

  • Java experience: I don’t think that you need to know loads of Java to develop Android apps but I would say it is important that you at least know the syntax and roughly how to do things. Experience in a similar language like C# or C++ would probably get you by, just so long as you know the difference between a package, class and that kind of thing
  • Experience in another object-orientated language: Some experience in another language would also be useful because despite the fact that most Android development is in Java it is useful to understand how other languages do things because a lot of the Android specific Java has had influence from C++
  • An understanding of how apps work: This would probably come with programming experience but you really aren’t going to get anywhere if you don’t get how the most basic apps. Reading a few tutorials can help fix this
  • Experience creating user interfaces via code and and a visual designer: Android uses both XML layouts and pure Java code to create User Interfaces so provided that you have done something in both before you’ll probably be fine. I should imagine that it would probably be OK if you’ve done JavaScript DOM and HTML
  • Basic knowledge of XML and SQLite: You won’t need to know how to do these perfectly but so long as you can create XML documents and edit them. I wouldn’t say SQLite knowledge is vital but it would be good to have some database knowledge
  • A basic understanding of other mobile platforms: I had done a tiny amount of iOS and Windows Phone development before starting Android which probably helped me a tiny bit because it gives you some knowledge of design. Windows Phone development is probably more different to Android than iOS, so even if you’ve just created a calculator in iOS you’ll be in a good position to start Android development
  • Good resources for testing: The emulator is good but I’ve found that it always useful to either have at least one Android device for testing. I also recommend setting up a few different devices in the emulator with different screen sizes and versions of Android because that will give you a chance to test in loads of different environments
  • You’ve read some stuff on Android development: It is worthwhile reading up on Android development before you get started. Android Design and the Android Guide are both good places to start and reading some blogs will probably help develop your ideas. If you get stuck, make sure that you go on Stack Overflow.

Once you are fairly confident with all of this I recommend going over to Lars Vogel’s site which has some great development tutorials.

HTML5 Canvas Particles

I was playing around with HTML5 this morning and decided to build a sort of particle simulation based on rules of Math rather than Physics. It was purely experimental but it looks quite cool. I won’t go into the exact rules of how the particles move around but it is based on some pretty trigonometry. Currently when I click the particles move to a new location however they always jiggle a little in their place. I plan to make it a little more advanced in the next week or so and release an Android version on the Android Market.

Building a simple blogging system in PHP – Part 2

In yesterday’s section of the tutorial we considered the basic layout, CSS and database structure. Today we are going to build the initial code that will fetch posts and other information. The previous tutorial ended looking like this:

Clearly there wasn’t any information so we need to begin adding things. The first thing we should do before doing anything else is to add some sample data to the database so that we can begin creating code that works. I added the following:

  • A blog post with the title ‘My first blog post!’ and the link My_first_blog_post along with some basic content
  • I added the category ‘life’ to the category table by adding a row with Id 1, Category life and Post 1 (links with the post table)
  • I added some tags the same way I added categories

The next simple bit of code to be run is to fetch a category list to display on the sidebar. I wrote the following code in code.php:

$pdo = new PDO("mysql:host=localhost;dbname=myblog", "root", "");
$pageTitle = "My Blog";
$pageContent = "";
$categoryList = "<ul class=\"category-list\">";
foreach ($pdo->query("SELECT DISTINCT Category FROM categories ORDER BY Category ASC")->fetchAll() as $cat)
 $categoryList .= "<li><a href=\"http://localhost/myblog/category/" . $cat[0] . "\">" . $cat[0] . "</a></li>";
$categoryList .= "</ul>";

Here’s a quick walkthrough of the code:

  • First we create a new PHP Data Object which is connected to the database we created. If you haven’t used PDO before it maybe worth looking it up in the PHP Manual
  • We then set default values for the variables and start an HTML list element in the $categoryList variable
  • We then loop through all the unique values in alphabetical order in the categories table and add them as a list item and link
  • We finish the list off

The end result of my sidebar is the following (I added some additional styling and layout stuff):

In the database I had all the category names as lowercase however CSS can style these as an uppercase letter at the beginning of each word. Now we need to look back at how the URLs work.

We have already established that the server will direct everything that doesn’t exist already into index.php to give us clean URLs. We therefore need to write some code that will interpret the requested URL. We also need to consider that we are including an RSS feed feature which will mean that people can subscribe to the site. I have therefore including the code that will generate the feed:

$url = explode("/", substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], "myblog/")+7));
if ($url[0] == "feed" || $url[0] == "rss")
 header("Content-type:application/rss+xml; charset=ISO-8859-1");
 echo "<?xml version=\"1.0\"?>\n";
 echo "<rss version=\"2.0\">\n";
 echo "<channel>\n";
 echo "<title>My Blog</title>\n";
 echo "<link>http://localhost/myblog/</link>\n";
 echo "<description>The source of information about my life!</description>\n";
 echo "<language>en-us</language>\n";
 foreach ($pdo->query("SELECT * FROM posts ORDER BY Posted DESC LIMIT 0, 20")->fetchAll() as $row)
 echo "<item>\n";
 echo "<title>" . $row['Title'] . "</title>\n";
 echo "<link>http://localhost/myblog/post/" . $row['Link'] . "</link>\n";
 echo "<description><![CDATA[" . $row['Content'] . "]]></description>\n";
 echo "<pubDate>" . date('D, d M Y H:i:s O', strtotime($row['Posted'])) . "</pubDate>\n";
 echo "</item>\n";
 echo "</channel>\n</rss>";

I won’t explain what all the code that generates individual items of XML does, but here is roughly what happens:

  • We get everything in the URL after the myblog/ part and split it where there is a forward slash character
  • We check if the first part of the URL is feed or rss and if it is send an XML header
  • Echo the initial required data about the feed
  • Loop through the twenty most recent items and print the required details – note that the date has to be first passed into a PHP date and then into a valid RSS date
  • If the feed wasn’t requested, continue running code.

The next stage of code is rather massive but gives us the core stuff for the blog and goes inside that last else statement. I won’t chunk it out into sections so here is the block:

if (isset($_GET['p'])) $page = ((int)$_GET['p'])-1;
 else $page = 0;
 if ($page < 0) $page = 0;
 if ($url[0] == "post")
 if (isset($url[1]))
 $post = $pdo->prepare("SELECT * FROM posts WHERE Link = :link");
 $post->execute(array(":link" => $url[1]));
 else header("location:http://localhost/myblog/");
 else if ($url[0] == "category")
 if (isset($url[1]))
 $post = $pdo->prepare("SELECT * FROM posts WHERE Id = ANY (SELECT Post FROM categories WHERE Category = :cat) ORDER BY Posted DESC LIMIT " . $page*10 . ", 10");
 $post->execute(array(":cat" => $url[1]));
 else header("location:http://localhost/myblog/");
 else if ($url[0] == "tag")
 if (isset($url[1]))
 $post = $pdo->prepare("SELECT * FROM posts WHERE Id = ANY (SELECT Post FROM tags WHERE Tag = :tag) ORDER BY Posted DESC LIMIT " . $page*10 . ", 10");
 $post->execute(array(":tag" => $url[1]));
 else header("location:http://localhost/myblog/");
 else $post = $pdo->query("SELECT * FROM posts ORDER BY Posted DESC LIMIT " . $page*10 . ", 10");
 if ($post->rowCount() > 0)
 foreach ($post->fetchAll() as $row)
 if ($url[0] == "post") $pageTitle = $row['Title'];
 $pageContent .= "<article>";
 $pageContent .= "<header><h2><a href=\"http://localhost/myblog/post/" . $row['Link'] . "\">" . $row['Title'] . "</a></h2><p>" . date('j F Y', strtotime($row['Posted'])) . "</p></header>\n";
 $pageContent .= $row['Content'];
 $cats = $pdo->prepare("SELECT Category FROM categories WHERE Post = :post");
 $cats->execute(array(":post" => $row['Id']));
 if ($cats->rowCount() > 0)
 $pageContent .= "\n<p>Posted in: ";
 foreach ($cats->fetchAll() as $cat)
 $pageContent .= "<a href=\"http://localhost/myblog/category/" . $cat[0] . "\" class=\"category-link\">" . $cat[0] . "</a> ";
 $pageContent .= "</p>";
 $tags = $pdo->prepare("SELECT Tag FROM tags WHERE Post = :post");
 $tags->execute(array(":post" => $row['Id']));
 if ($tags->rowCount() > 0)
 $pageContent .= "\n<p>Tagged with: ";
 foreach ($tags->fetchAll() as $tag)
 $pageContent .= "<a href=\"http://localhost/myblog/tag/" . $tag[0] . "\" class=\"category-link\">" . $tag[0] . "</a> ";
 $pageContent .= "</p>";
 $pageContent .= "</article>";
  • The first thing that happens is checking if the p variable is set – this tells the user what page they are on
  • If we are looking at an individual post, prepare a query for that post
  • If we are looking at a category, prepare a query for that category
  • If we are looking at a tag, prepare a query for that tag
  • Loop through all the posts and produce the appropriate HTML for them

In reality it is actually relatively simple, it just takes quite a bit of code to work correctly. Here is what the finished result looks like, although you may want to add extra styling:

In the next tutorial we’ll add commenting and a basic admin panel.

Building a simple blogging system in PHP – Part 1

Today there are many blogging systems available to create a blog such as WordPress, Blogger and Tumblr however it can be more rewarding to build your own blogging system that you can use directly in your website. This set of tutorials will go through the procedure of building a blogging system with tags, categories and RSS using PHP and MySQL because they are both easily accessible environments. If you do not have either of these available on your system I recommend that you download WampServer and go through some PHP tutorials because that is what I will be using along with NetBeans 7.1 RC2 for coding.

Initial considerations

A blogging system has a few basic requirements. Here is what I think they are:

  • Simplistic two column layout – the left is for posts and the right is for a sidebar including category links, recent posts, RSS and search
  • Ability to fetch many posts or individual posts
  • Ability to tag a post with as many tags as required and as many categories as required
  • RSS feed automatically generated
  • Commenting on posts
  • Admin panel for editing
  • Well structured database for storing data

Clearly a blogging system is quite a large project and it is important to carefully consider how you will build it. In part 1 of this tutorial I shall develop the appropriate tables in a database, setup the server and basic layout of the pages.

Making the database

For simplicity I created a database called myblog in PHPMyAdmin on WampServer. I created the following tables:

  • posts
    • Title TEXT
    • Link TEXT
    • Content TEXT
    • Posted DATETIME
  • categories
    • Category TEXT
    • Post INTEGER
  • tags
    • Tag TEXT
    • Post INTEGER

Incredibly this is all that we need in our database because we will be taking advantage of other web services to manage things like commenting. The next stage involves configuring Apache.

Configuring Apache

Apache is the web server of the web because its free and it does the job. Before we move on it is worth considering how we wish URLs on the blog to appear. One option is to have something like blog/post.php?id=3 to direct to the third blog post in the database however this is a cumbersome old school approach that is not used on many websites. Instead we will have something like blog/post/My_blog_post. Before we do this we first need to do a few things. The first is to ensure that the rewrite_module is enabled in Apache. In WampServer this can be done by clicking the WampServer icon in the taskbar, clicking Apache, clicking Apache Modules and then ensuring there is a tick against the rewrite_module. You then need to navigate to where you intend to put your blog (I’ve created a folder called myblog in C:\wamp\www) and create a new file called .htaccess and put in the following:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+) - [PT,L]
RewriteRule ^(.*) index.php

These five lines of code basically (I won’t go into detail) cause everything that doesn’t exist on the server (such as image files) in the directory to go through index.php which is where our basic code will be stored.

Creating index.php

For simplicity purposes this is where we are directing the server to for requesting posts. I’ve created the following in the file:

<?php include("code.php"); ?>
<!DOCTYPE html>
 <link rel="stylesheet" type="text/css" href="http://localhost/myblog/css.css" />
 <title><?php echo $pageTitle ?></title>
 <div id="page">
 <div id="header">
 <h1>My blog</h1>
 <h3>The source of information about my life</h3>
 <div id="header-image">&nbsp;</div> 
 <div id="page-content">
 <div id="left">
 <?php echo $pageContent ?>
 <div id="right">
 <a href="http://localhost/myblog/rss" id="feed-link">Feed</a>
 <?php echo $categoryList ?>
 <div id="footer">My blog was created by Programming Thomas</div>

There is very little to observed from this other than it defines our basic layout. It is worth noting that the links have to be full lengths because they will not have the same relativity in localhost/myblog/post/My_post_name and localhost/myblog. I also created code.php and gave the variables some default variables so that I could view the page without errors. Here is what it looked like after styling:

I decided to use Google Web Fonts to get the Open Sans font which I thought looked quite nice. The image is from Flickr however I’ve cropped it. Here is the full CSS (I’ve tried to make it as small as possible):

@import url(;
 font-family:"Open Sans", sans-serif;
 margin:10px auto;
#header h1, #header h3
 background:url( center center;
 margin:5px 0;
 background:url("http://localhost/myblog/feed-icon-28x28.png") no-repeat;
 padding:0 0 0 33px;

I think that is all that we will do today, check back tomorrow for Part 2 of the tutorial.