Sunday, January 31, 2010

How to populate a Spinner widget from an Array

Lets say we have an Array of colours, defined in a xml file in our res folder in our Eclipse project, like below.

<?xml version="1.0" encoding="utf-8"?>
<string name="hello">Hello World, droidTest1!</string>
<string name="app_name">droidTest1</string>

<string-array name="colours">

Spinners are Android's implementation of a dropdown menu, of sorts.
How do we insert these values into a spinner widget?

First, we need to create a layout for our Spinner widget, so it has a user interface.
We could do this is code, but the more accepted method is to define our layouts for Android applications in XML files, located in our res/layout folder in our project.







Then we create an instance of the Spinner class,

Spinner colourSpinner = (Spinner) findViewById(;

Next we create an ArrayAdapter to wrap our xml array (Array of colours) and we put some pre-defined styles.

ArrayAdapter adapter = ArrayAdapter.createFromResource( this, R.array.colors, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

And we set the ArrayAdapter to our instance of the Spinner class:

And when we run our application:

The closed Spinner Widget

.. When selected shows us out colour options.

Aaah.. Sweet Androidy Success!


Saturday, January 30, 2010

Android Adapters: an introduction

An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set.

An AdapterView is a view whose children are determined by an Adapter.

Some examples of AdapterViews are ListView, GridView, Spinner and Gallery.

There are several types or sub-classes of Adapter:

ListAdapter: Extended Adapter that is the bridge between a ListView and the data that backs the list. Frequently that data comes from a Cursor, but that is not required. The ListView can display any data provided that it is wrapped in a ListAdapter.

ArrayAdapter: A ListAdapter that manages a ListView backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView.

CursorAdapter: Adapter that exposes data from a Cursor to a ListView widget. The Cursor must include a column named "_id" or this class will not work.

HeaderViewListAdapter: ListAdapter used when a ListView has header views. This ListAdapter wraps another one and also keeps track of the header views and their associated data objects.
This is intended as a base class; you will probably not need to use this class directly in your own code.

ResourceCursorAdapter: An easy adapter that creates views defined in an XML file. You can specify the XML file that defines the appearance of the views.

SimpleAdapter: An easy adapter to map static data to views defined in an XML file. You can specify the data backing the list as an ArrayList of Maps. Each entry in the ArrayList corresponds to one row in the list.

SimpleCursorAdapter: An easy adapter to map columns from a cursor to TextViews or ImageViews defined in an XML file. You can specify which columns you want, which views you want to display the columns, and the XML file that defines the appearance of these views.

SpinnerAdapter: Extended Adapter that is the bridge between a Spinner and its data. A spinner adapter allows to define two different views: one that shows the data in the spinner itself and one that shows the data in the drop down list when the spinner is pressed.

WrapperListAdapter: List adapter that wraps another list adapter. The wrapped adapter can be retrieved by calling getWrappedAdapter().

Android applications: Components and Structure

Android extends the standard views/data model, providing a new model that is suitable for equipment activated at all times.

The structure of an Android application is defined as follows:

The file AndroidManifest.xml

This defines the components of the application and their relationships. It gives the permissions to application as to what it can do with users. It can also give permission to components of the application.

The views (Class android.view.View)

The interface of a program for Android is a tree of views.

Activity ( class)
This is something that the user can do, translated into program. It corresponds to a screen, but can have multiple views.

Intent (android.content.Intent class)
Describes an action which must be performed.

Service ( )
Program that operates in background.

Content Provider (android.content.ContentProvider class)
Encapsulates data and provides them commonly to several programs.

Notification ( and classes)
Class which informs the user about what is happening.

Besides components, there are also resources that can be XML files, image files as jpeg, etc. These use the android.content.Resources interface and are stored in the res directory.

Components of an Android application

Each component is included in a list stored in the manifest file AndroidManifest.xml of each application.


An activity corresponds to a screen. If an application is composed of several screens, it has an activity for each screen. Each activity is a class that extends the base class Activity. It has a graphical user interface made of views, and it responds to events. When you change screen, a new activity is launched.
It can return a value. For example, if an activity can choose something, text, image, it returns what is chosen.

The graphical interface of an activity is described by a Layout:
- Full screen.
- Float: dialogue or alert.
- None. In this case it works in background and is invisible. It is maked visible by giving it a layout.

Note that the graphical user interface is described in XML as XUL and XAML.


The intents are the goals of applications and are made effective by a new screen. An intent is made up of an action and data that are URI.

Examples of actions: MAIN, VIEW, EDIT, PICK.
If one wants to see a card about a person, an intent is defined. The action is VIEW and the data is the URI which enables access to this card.

IntentFilters describes how the action should apply.

IntentReceiver is an object that responds to external events. It can operate in the application or it can start an application.

Example of intent, view a webpage: VIEW for action and for data


A service is designed to operate independently of the screen, thus of activities. The best example is the music player that can works while moving from one screen to another.

Content Provider

Data stored by a computer program, in the form of files or SQLite databases are private and may not be used by other applications.
But Content Provider may be used to share data among several applications. The interface ContentResolver is the interface that provides data to other objects.


The class defines how an event must be notified to user: displaying an icon, changing state of a led, vibration, or others. While the class sends the message in the form so defined.

Thursday, January 28, 2010

Inspiration: 50 Android games in one video..


- homerunbattle 3d
- speed forge 3d
- radiant
- flight director
- Zen Table Tennis
- tank ace 1944
- sky force
- Shoot U!
- Armageddon Squadron
- Light Racer 3D
- gang wars
- Wave Blazer
- death ride
- head to head racing
- avatar
- Farm Frenzy
- light racer
- Family Guy Uncensored
- super boom boom
- toonwarz
- air hockey
- meteor
- what the doodle!?
- Raging Thunder
- the settlers
- lightup
- the game of life
- military madness
- bebbled
- jump santa jump
- diner dash
- brain challenge
- assassins creed
- space physics
- million dollar poker
- derek jeter 2009
- armored strike
- robo defense
- guitar hero
- air attack
- wpt texas hold'em
- de Blob
- papastacker
- spades
- spore
- tennis slam
- Iron Sight
- tower bloxx
- mechanics touch
- TightRope Hero
- flying aces

Game Developers Conference 2010 organizers have announced that they are working together with Google "to celebrate and inspire the mobile and independent game development communities" by offering free Nexus One and Verizon Droid by Motorola phones to select attendees.

The newly announced offer, part of Google's outreach into the mobile phone space as it expands use of its Android operating system, is open to qualifying developers who register to attend GDC 2010 by February 4th, 2010.

The Game Developers Conference, as the world’s largest professional-only game developer event, has been at the center of the industry’s discussions on these topics.

It serves as home to major Summits such as the GDC Mobile/Handheld Summit and the Independent Games Summit, as well as the IGF Mobile competition to award handheld game innovation.

In recent years, the smartphone has become one of the most widespread and widely-used game platforms, and has proven particularly suited to independent developers experimenting with new and unusual gameplay.

As an official statement on the tie-in notes: "This makes conference attendees great potential developers of new content for phones using the Android operating system." Alongside the announcement, Google's Eric Chu has posted about Android's GDC 2010 presence on the official Android Developers weblog.

"At the GDC, we are constantly looking for ways to help the game development community learn and thrive. The mobile and independent game spaces having been providing so many of those opportunities for years now," said Meggan Scavio, event director of the Game Developers Conference. "We are so appreciative that we can better reach those goals by actually putting a new opportunity – Android-powered devices – into the hands of our attendees."

Early Bird rates for GDC 2010 end February 4. For more information about the 2010 Game Developers Conference, including the eight summits and the Android phone promotion, please visit the official Game Developers Conference website.

Sunday, January 24, 2010

Creating multiple sqlite database tables in Android

Most of the Android database examples you will find on the web will usually contain only one table to demonstrate the basic database concepts.

That's great, the only problem with this is that most non-trivial database implementations will contain more than one table.

The standard database creation string for a single table will probably look a lot like the below:

private static final String CREATE_TABLE_1 =
" create table " + table1 +
" (_id integer primary key autoincrement," +
" title text not null, body text not null);";

Which is called in your DB Adapter class like this:

public void onCreate(SQLiteDatabase db) {


So what to do if you want to create more than one table?
You may do the below.. but will it work?
Note that this is one big string containing three separate create statements...

private static final String DATABASE_CREATE_MULTIPLE_TABLES =
" create table " + ITEMS_TABLE +
" (_id integer primary key autoincrement," +
" title text not null)" +

" create table " + TAGS_TABLE +
" (_id integer primary key autoincrement," +
" tagName text not null)" +

" create table " + LOCATIONS_TABLE +
" (_id integer primary key autoincrement," +
" locationName text not null, gpsCoOrds text);"

And then you try calling them in your DB Adapter class like so:

public void onCreate(SQLiteDatabase db) {


So you're trying to create the three tables in one call to db.execSQL.

This appears to compile and run successfully, you can even read and write to the FIRST table that is created, but..
..when you try to read or write to any other table you will see the dreaded

'Sorry! The application Kdkddfblah (process test.Kdkddfblah) has stopped unexpectedly. Please try again'

..error message.


If you debug your application, you might see references to syntax errors 'near create', and possible a reference that the table doesn't exist.

Hmm... What went wrong?

The answer is that sqlite, and therefore the db.exec method, only lets you execute one sql command at a time. We were trying to run three sql statements in one go in db.execSQL(DATABASE_CREATE_MULTIPLE_TABLES);.

So what you need to do to fix this is move each of the above table create statements into their own strings, like this (Note that this now creates three seperate strings, unlike above):

private static final String CREATE_TABLE_1 =
" create table " + table1 +
" (_id integer primary key autoincrement," +
" title text not null, body text not null);";

private static final String CREATE_TABLE_2 =
" create table " + TAGS_TABLE +
" (_id integer primary key autoincrement," +
" tagName text not null)";

private static final String CREATE_TABLE_3 =
" create table " + LOCATIONS_TABLE +
" (_id integer primary key autoincrement," +
" locationName text not null, gpsCoOrds text);";

.. and then use these strings in your onCreate method like below, this then works.

public void onCreate(SQLiteDatabase db) {


If you find this doesn't work for you, try dropping all the tables in your database and try again, or give the database a different name, or different version number. The SQLiteOpenHelper seems to have some troubles registering that the database is to be changed. It finds a db with the same name and version number, goes 'meh' and doesn't look to see if the structure is different at all.

You can also pull the sqlite db file right off your device (or emulator) by going into the DDMS perspective in Eclipse (Window menu\ Open perspective \ Other \ DDMS), navigating to the database file which will probably be at \data\data\*Your Application Name*\databases.

There's a 'pull file' button on the top left as seen highlighted below:

.. You can then open the DB in your favourite sqlite manager (I like Sqliteman) and play around. Can can also of course, push the file back to the device if you wish.

Monday, January 18, 2010

Psst..Remember that your layout files must have lowercase names..

Remember that your layout files must have lowercase names, or they won't show up in your autoComplete list of options after 'R.layout' in Eclipse when you try this :


The file won't actually show up as having any errors in your package explorer (on the right by default in the IDE), but if you look down in the console (by default down the bottom), you'll see this:

Invalid file name: must contain only [a-z0-9_.]

You might see an error on your project name, but with all the folders and files it can be hard to track down the cause.

When you try to run your application you will see:

'Your project contains error(s) please fix them before running your application'

.. and it won't be happy until you delete the offending file, even if you're not actively referencing it in your code.

Hope that helps.. Happy coding!

Sunday, January 17, 2010

Errors trying to run ADB (Android Debug Bridge)?

The Android Debug Bridge (adb) is a tool lets you manage the state of an emulator instance or Android-powered device.

I was trying to run it for the first time on my ubuntu 9.10 box and I kept getting this error:

desktop:~/dev/Android/android-sdk-linux/tools$ adb
No command 'adb' found, did you mean:
Command 'cdb' from package 'tinycdb' (main)
Command 'gdb' from package 'gdb' (main)
Command 'aub' from package 'aub' (universe)
Command 'dab' from package 'bsdgames' (universe)
Command 'mdb' from package 'mono-debugger' (universe)
Command 'arb' from package 'arb' (multiverse)
Command 'tdb' from package 'tads2-dev' (multiverse)
Command 'pdb' from package 'python' (main)
Command 'jdb' from package 'openjdk-6-jdk' (main)
Command 'jdb' from package 'sun-java6-jdk' (multiverse)
Command 'ab' from package 'apache2-utils' (main)
adb: command not found

What was I doing wrong?

A quick google search shows me the error of my ways.. I haven't added my Android SDK tools directory to my system path!

It should go something like this...

open a terminal window and type:

$ echo $PATH
---(should return the directories associated with $PATH)

$ export PATH=$PATH:/home/YOUR-USERNAME/sdk/tools
---(replace with path to your tools directory, you may need to add 'sudo' to the beginning of this cmd)
Update: later versions of the SDK have ADB moved to the platform-tools directory, so adjust the above accordingly.

$ echo $PATH
---(you should now see your tools directory added to the end of the $PATH variable)

$ adb devices
---(now adb should do something, if nothing else at least error, no devices)

And now I get:

List of devices attached
emulator-5554 device

Sweet Success!

p.s. Adding to the system path in Windows is along the lines of :
  1. right-click '(My) Computer'
  2. Select 'Properties'
  3. Go to 'Advanced' or whatever tab you find 'Environment Variables'
  4. Select 'Path' then 'Edit' and add your new path in.
Update: if you are using 64-bit linux you may need to also install the ia32-libs package like so:

sudo apt-get install ia32-libs

Thursday, January 14, 2010

Including layouts: a working example

Here's a working example of including one layout inside another.

Let me know if you have any issues or questions.
This works with, and probably requires, a AVD version of 2.1 or thereabouts.

contents of

package androidforbeginners.droidTest1;

import android.os.Bundle;

public class droidTest1 extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {

contents of main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
android:text="combining layouts"

<include android:id="@+id/cell1" layout="@layout/layout2" />
<include android:id="@+id/cell2" layout="@layout/layout3" />


Contents of layout2.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

Contents of layout3.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""


You could also include multiple occurrences of the one layout in your main.xml like this if you wanted:

contents of main.xml (revised):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
android:text="combining layouts"

<include android:id="@+id/cell1" layout="@layout/layout2" />
<include android:id="@+id/cell2" layout="@layout/layout2" />
<include android:id="@+id/cell3" layout="@layout/layout2" />
<include android:id="@+id/cell4" layout="@layout/layout2" />


Although if you do this, I can't see a way to reference individual repeating items.
I think include is more including a single layout across multiple Activities.

Let me know in the comments if you know a way.

Till next time: Enjoy!

Tuesday, January 12, 2010

Layout Tricks: Creating Reusable UI Components

The Android platform offers a wide variety of UI widgets, small visual construction blocks that you can glue together to present users with complex and useful interfaces. However applications often need higher-level visual components. To meet that need, and to do so efficiently, you can combine multiple standard widgets into a single, reusable component.

For example, you could create a reusable component that contains a progress bar and a cancel button, a panel containing two buttons (positive and negative actions), a panel with an icon, a title and a description, and so on. You can create UI components easily by writing a custom View, but you can do it even more easily using only XML.

In Android XML layout files, each tag is mapped to an actual class instance (the class is always a subclass of View, The UI toolkit lets you also use three special tags that are not mapped to a View instance: <requestFocus />, <merge /> and <include />. This article shows how to use <include /> to create pure XML visual components.

The <include /> element does exactly what its name suggests; it includes another XML layout. Using this tag is straightforward as shown in the following example:



<include android:id="@+id/cell1" layout="@layout/workspace_screen" />
<include android:id="@+id/cell2" layout="@layout/workspace_screen" />
<include android:id="@+id/cell3" layout="@layout/workspace_screen" />


In the <include /> only the layout attribute is required. This attribute, without the android namespace prefix, is a reference to the layout file you wish to include. In this example, the same layout is included three times in a row. This tag also lets you override a few attributes of the included layout. The above example shows that you can use android:id to specify the id of the root view of the included layout; it will also override the id of the included layout if one is defined. Similarly, you can override all the layout parameters. This means that any android:layout_* attribute can be used with the <include /> tag. Here is an example:

<include android:layout_width="fill_parent" layout="@layout/image_holder" />
<include android:layout_width="256dip" layout="@layout/image_holder" />

Monday, January 4, 2010

Getting started with Android Development using Eclipse

The Google Android platform offers a easy and quick way to develop applications for the mobile device. First of all, lets start with the tools we will need to start developing our own Android applications.

The best IDE (Integrated development environment) t to develop Android is Eclipse.

The Android SDK

We will need another tool to work with Android. This tool is called the SDK (Software Development Kit), we have download it from here and place in somewhere handy on your computer (C:/Android/SDK if we are on Windows, for example, or ./home/YOURUSERNAME/Android/SDK if we use a *nix system).

It doesn't really matter where you put it, just don't forget where, because in next steps we will have to enter the path to the SDK into the Eclipse environment.


Once we have downloaded the SDK we will need the Android plugin for Eclipse. There are a couple of different ways of doing this, depending of the version of Eclipse you are using:

For Eclipse Ganymede :

* Start Eclipse.
* In the Menu, select "Help" and then "Software Updates".
* In the new pop-up window, push the button "Add site ... " and enter the following address and click Ok:

* Once this is done, you have to go back to the Updates and Add ons menu. The location we have entered before should appear, click on it, check the "Developer Tools" and click Install.
* Follow the steps to install the plugin.

For Eclipse Europa version

* Start Eclipse
* In the Menu, select "Help" , "Software Updates" and then "Find and Install".
* Click on New Remote Site
* In the new pop-up window, paste '', and click Ok:

* One this is done, the new site should appear in the Add ons list. Click on it and check both “Android Developer Tools” and “Android Editor”.
* Follow the steps to install the plugin.

Hint: If the doest work try "http" instead of "https".

Once we have installed the Eclipse plugin we have to restart the IDE. Now, its time to point to the plugin where the SDK is in our system.

In the Menu, “Window”, select “Preferences”. Select Android from the left panel, click the “Browse” button and locate the SDK directory in your computer, then click OK.

Now we are able to create Android applications on our Eclipse IDE.