Friday, May 21, 2010

How do I – Android: create a ListView control

Android has a nice control to display data as list called ListView. It’s very easy to use. First of all, put a <ListView /> on form (in your markup xml). Then, attach adapter, that will provide data for your list view, in code, hook up click (and long click) listeners, and that’s it. Unless you need something fancy (which you can definitely do :)). Check out the example below.

1. Declaring list view in xml markup:

File: main.xml

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

2. Declaring a list view item – I’m going to use a ArrayAdapter to populate listbox and it requires a TextView resource to be specified as one of the .ctor parameters:

File: list_item.xml

<?xml version="1.0" encoding="utf-8"?>

Please notice that this TextView element was declared in separate file – list_item.xml.

3. Hook up your list view in code:

package org.example.demo;

import android.os.*;
import android.view.*;
import android.view.ContextMenu.*;
import android.widget.*;
import android.widget.AdapterView.*;


public class Demo extends Activity implements OnItemClickListener {
      private final String[] monthList = new String[]
{ "January", "February", "March", "April", "May"
              "June", "July", "August", "September",
       "October", "November", "December" };

      public void onCreate(Bundle savedInstanceState) {

            // Initialize list.
            ListView list = (ListView) this.findViewById(;
            list.setAdapter(new ArrayAdapter<String>(this,
R.layout.list_item, monthList));


      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            // Handle list clicks.

      public void onCreateContextMenu(ContextMenu menu, View v, 
ContextMenuInfo menuInfo) {
            // Create context menu.

One comment about code: please notice that how we referenced item template – R.layout.list_item!

You can find more information about ListView and Adapter in Adroid Documentation.


Sunday, May 9, 2010

How do I – Android: launch another activity (from my project)?

You use intents to start an activity. Intent describes what exactly you want to do.

I you want to launch an Activity within your project you need to do the following:

1. Lets say you have an Activity “” with button and “” – second activity that you want to show when user presses on a button.

2. Define a new intent passing current context (your current activity is an inheritor of a Context) and your target activity’s class name (Second.class in this case).

3. Call startActivity method passing an instance of the Intent created before:

private void onShowViewClick() {
      Intent newActivityIntent = new Intent(this, Second.class);

Now, when you click on a button – a new activity will be started.

Don’t forget to declare your activity in AndroidManifest.xml.

How do I – Android: create a new activity?

Only a very simple applications consist of one form (activity). To create new activity in Android (Eclipse) follow these steps:

1. Open your project in Eclipse
2. Expand your project folder structure down to the “layout” folder and call a context menu on this folder:


3. Select “New” –> “Android XML File” from context menu:


4. Once you click this menu item a new Android XML file dialog will be opened where you will need to fill at least “File” field, all other fields are optional.


Press “Finish” and you will get a new activity in your Android project.

Well, now when you have your layout defined, you need to create a class representing this activity (it is not necessary in some cases)..

To create a new class that will be used to show your activity just defined on screen you need to:

1. Select “File” –> “New” –> “Class…”
2. Specify source folder and package name – by default that will be “src” folder under your project tree;
3. Provide name for you class – its better to give your class name same as you gave your layout file (for instance, if your layout name is “aboutform.xml”, than name your class “”);
4. Specify superclass – the one that you want to inherit from – it must be;


5. Press “Finish…”

Now, when you have your class and layout – you need to “connect” layout and class. You can do that by specifying which layout your activity must use in onCreate method of your activity.

1. Override onCreate method, put the following code in your activity class:

import android.os.Bundle;


public class Second extends Activity {
      public void onCreate(Bundle savedInstanceState) {
            // ...

Read more about activity lifetime here!

A sidenote: when you create a new layout an Eclipse automatically regenerates a resources and puts a new resource identifier in R class (can be found in “gen” folder under your project tree). For instance, you’ve added a new layout with name “second".xml”, it means that when R file will gets regenerated you will see a new resource R.layout.second and it will be available from your code (as your layout identifier).

2. To specify which layout must be displayed use setContentView method and specify target layout Id:


Final version should look like the following:

import android.os.Bundle;

public class Second extends Activity {
      public void onCreate(Bundle savedInstanceState) {

That’s all, you can use your activity.

How do I – Android: create a new project?

To create a new Android project in Eclipse do the following: click “File” –> “Android Project”.


You will get following window:


Fill out the following fields:

Project name – your project name;
Build target – select one of the build target that you want to use (if you need some Google-specific features, like maps, select “Google APIs”, it will include all Android features plus some additional functionality);
Package name – your package name (it must consist at least from two parts – something like “orgname.projname”);
Create Activity (checkbox and field) – Check this checkbox if you need an activity to be created along with project; If you need new activity – provide a target activity’s name, otherwise uncheck this checkbox;
Min SDK Version – minimum required Android SDK version.

Press Finish (or Next if you need a test project) and that’s it!

Tuesday, May 4, 2010

How do I – Java: get current date/time in UTC format

To get date/time in UTC format you’ll need two classes java.text.SimpleDateFormat and java.util.TimeZone.

Create an instance of the SimpleDateFormat passing a desired format and set a time zone for it (by calling TimeZone.getTimeZone with “UTC” value).


SimpleDateFormat formatUTC = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ssZ");


return formatUTC.format(new Date());

Note: Using “GMT” time zone you can get time in GMT format.

How do I – Eclipse: generate getter/setter for class fields

Its a good practice to keep your class fields private. But declaring getter/setter for each field may be a time consuming (and boring) operation, for instance, if you have more than 3 private class fields.

But, Eclipse has a nice helper mechanism of generating getters/setters automatically from your class fields.

Lets say we have class Animal with 4 fields and we want to generate getters (and setters) for them:


public class Animal {

      private int age;

      private String kind;

      private int weight;

      private Color color;


Open context menu and select “Source” –> “Generate Getters and Setters…”.


You will get the following dialog:


Configure your fields and press OK and you will get your getters/setters generated for you.

Happy Eclipse’ing

How do I – Eclipse: Expand/collapse all methods

To expand or collapse all methods Eclipse has following keyboard shortcuts:

Collapse All - Ctrl+Shift+/

Expand All - Ctrl+Shift+*

Happy Eclipse’ing..

Monday, May 3, 2010

How do I – Eclipse: Create a user spell checking dictionary

You know that Eclipse has built in spell checker, but what if you want to add some very specific words to spellchecker (and you want them to be treated as valid words).

For example, I want “Javadoc” keyword, that appears in comment , to be a valid word for Eclipse (I know what “Javadoc” means and I don’t want it to be underlined with red):


Solution – create a user dictionary.

First of all, create a .txt file somewhere on file system, then go to “Window” –> “Preferences”. An then: “General” –> “Editors” –> “Text Editors” –> “Spelling” and specify the full path to the file just has been created in “User Defined Dictionary” field.


Press “OK” and you’re done. Now you can add words to your custom dictionary.

Move your mouse over the word with spelling warning and you’ll see the following:


Select “Add {your_word} to dictionary” and … that’s it!

Happy Eclipse’ing :)