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=http://schemas.android.com/apk/res/android
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
      <ListView
            android:id="@+id/demoList"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#FFFFFFFF">
      </ListView>
</LinearLayout>

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"?>
<TextView
      xmlns:android=http://schemas.android.com/apk/res/android
      android:id="@+id/itemText" 
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:padding="10px">
</TextView>

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.app.*;
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" };

      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

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

 

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

      @Override
      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.

Cheers!

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 “MainActivity.java” with button and “Second.java” – 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);
      this.startActivity(newActivityIntent);
}

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

NOTE:
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:

image

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

image

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.

image

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 “aboutform.java”);
4. Specify superclass – the one that you want to inherit from – it must be android.app.Activity);

image

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.app.Activity;
import android.os.Bundle;

 

public class Second extends Activity {
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(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:

this.setContentView(R.layout.second);

Final version should look like the following:

import android.app.Activity;
import android.os.Bundle;

public class Second extends Activity {
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            this.setContentView(R.layout.second); 
      }
}

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”.

image

You will get following window:

image

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).

Example:

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

formatUTC.setTimeZone(TimeZone.getTimeZone("UTC"));

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:

import android.graphics.Color;

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…”.

image

You will get the following dialog:

 image

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):

image

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.

image

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:

image

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

Happy Eclipse’ing :)