«

»

Jan 29

Print this Post

Android: Your first Android Application

So, you finally want to make you first Android Applications. But don’t be scared, we won’t start with the "Hello, World!" application usually used to introduce you into a programming language, but will start with something more useful: A login screen.

If you haven’t setup the SDK & Eclipse yet, you should first read my previous "Android: Installing the SDK" post and then come back.

All of the guides and examples are written with the Eclipse IDE. If you’re using another IDE, you have to check for appropriate menu/shortcut/etc options in your IDE.

First we create a new project by selecting the File menu -> New -> Android Project or right-clicking the Package Explorer -> New -> Android Project.

If you’re trying to add a new Android project for the first time, you may need to click New -> Project… and then select Android/Android Project from the list

After you have entered a project, package, activity and application name you can click Finish and get a "Hello World" project with all the vital parts to run it.

NewProjectDialog

The Package is just a unique identifier used to identify the application. You are free to choose a name, but there are naming conventions. The package usually consists of 3 parts.
prefix: usually org (for non-profit organizations) or com (commercial organization)
name: usually contains your name or your companies name (i.e. google, tseng, etc.)
label/category: usually used to classify the project more (i.e. maps, examples, api, interface, client, server)

Some good examples:
com.google.maps
com.google.examples
org.apache.http

Now that we have a project we could start coding, right? Not yet. Before writing the actual code, we first need to create our UI. There are two ways to create UI’s for Android:

  • By defining them in a XML file and inflate it within your application
  • By defining them programmatically

In this Tutorial we will use the former, as it’s easier and we have a much cleaner Code.

Usually you’ll want to create UI’s in this way and it works good. However in some cases (i.e. Custom Widgets) or dynamical Views, you’d like to make it programmatically, for performance reasons.

Open the main.xml file (you can find it in your project’s res/layouts/main.xml folder.

<?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"
    >
	<TextView  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="Please enter your login"
	    />
	<TextView  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="Login:"
	    />
	<EditText
		android:id="@+id/username"
		android:singleLine="true"
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	/>
	<TextView  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content"
	    android:text="Password:"
	    />
	<EditText
		android:id="@+id/password"
		android:password="true"
		android:singleLine="true"
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	/>
	<Button
		android:id="@+id/login_button"
		android:text="Login"
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	/>
	<Button
		android:id="@+id/cancel_button"
		android:text="Cancel"
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	/>
	<TextView
		android:id="@+id/result"  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content"
	    />
</LinearLayout>

So what does this mean?

First we have a LinearLayout element as root. There are several other Layouts (like RelativeLayout and TableLayout). LinearLayout is pretty easy to use and fits for the basic needs. A LinearLayout will either order the elements within it either horizontally or vertically. To learn more about the basics of Android Layout, please read "Creating XML UIs" article, before returning here, but it’s not necessary to understand this first tutorial. For now we the only important part are the IDs like android:id="@+id/username". We will need them later, to access the elements and change their attributes/content. They can be accessed via code by R.id.username.

Now we can save the file and start the real coding, so open the LoginExample.java file, which can be find in src/com.tseng.examples/LoginExample.Java and should look something similar to this:

package com.tseng.examples;

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

public class LoginExample extends Activity {
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

One thing to notice, is the setContentView(R.layout.main); line. This is the line which will loads the XML layout.

When you create a XML fine in res/layouts folder, ADT Tool also automatically generates an ID within the R.java file and is used to identify the resource

The file only consists of one class which extends the Activity class and a overridden onCreate method. The onCreate method will be called, when the activity is created. This is the place, where we need to load our UI and pick references to the elements within it.

First, we have to declare some Variables which will hold references to the objects we need.

	// Declare our Views, so we can access them later
	private EditText etUsername;
	private EditText etPassword;
	private Button btnLogin;
	private Button btnCancel;
	private TextView lblResult;

Next, we need to get the references and assign them to these variables. So we add the following code after setContentView(R.layout.main); line

        // Get the EditText and Button References
        etUsername = (EditText)findViewById(R.id.username);
        etPassword = (EditText)findViewById(R.id.password);
        btnLogin = (Button)findViewById(R.id.login_button);
        btnCancel = (Button)findViewById(R.id.cancel_button);
        lblResult = (TextView)findViewById(R.id.result);

It’s important that you add this code after setContentView(R.layout.main); otherwise you will get an exception and your application will crash. Reason for this is, that you can’t use findViewById() before you have a fiew, because the UI doesn’t exist before this call.

We’re using the ids from the resource file (R.java). Remember that android:id="@+id/username" at beginning of this post? That’s why we need this id field.

If you run your application now and click on any of the buttons, nothing will happen. So we also need to add events (in Java it’s called Listeners) to our two buttons. So we’ll add this code below

        // Set Click Listener
        btnLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Check Login
				String username = etUsername.getText().toString();
				String password = etPassword.getText().toString();
				
				if(username.equals("guest") && password.equals("guest")){
					lblResult.setText("Login successful.");
				} else {
					lblResult.setText("Login failed. Username and/or password doesn't match.");
				}
			}
		});
        btnCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Close the application
				finish();
			}
		});

The .setOnClickListener method accepts a OnClickListener variable which contains the reference to the function to be called when the event gets triggered. There are tree ways to implement an Listener. I’ve decided to use the inline anonymous class version, as every of the listeners only gets used once and their code is pretty small. If you want to know more check out my Implementing Listeners in Android/Java post.

For the Login button (btnLogin) we’re getting the values from both Text fields (etUsername containing the username and etPassword containing the password) and comparing them to the login. If both are correct, it will update the lblResult field with a message of successful login, otherwise informs the user that the login has failed.

For the Cancel button we simply close the Activity by calling finish();.

In this example we have the username and password hard-coded. In a real application we would receive the login from a webservice or an database.

The final code should look like this:

package com.tseng.examples;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class LoginExample extends Activity {
	// Declare our Views, so we can access them later
	private EditText etUsername;
	private EditText etPassword;
	private Button btnLogin;
	private Button btnCancel;
	private TextView lblResult;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set Activity Layout
        setContentView(R.layout.main);
        
        // Get the EditText and Button References
        etUsername = (EditText)findViewById(R.id.username);
        etPassword = (EditText)findViewById(R.id.password);
        btnLogin = (Button)findViewById(R.id.login_button);
        btnCancel = (Button)findViewById(R.id.cancel_button);
        lblResult = (TextView)findViewById(R.id.result);
        
        // Set Click Listener
        btnLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Check Login
				String username = etUsername.getText().toString();
				String password = etPassword.getText().toString();
				
				if(username.equals("guest") && password.equals("guest")){
					lblResult.setText("Login successful.");
				} else {
					lblResult.setText("Login failed. Username and/or password doesn't match.");
				}
			}
		});
        btnCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Close the application
				finish();
			}
		});
    }
}

Finally you can run your application and enter your "guest" as username and password and click on login.

If you’re getting errors like EditText cannot be resolved, it’s because you’re missing the proper imports. Pressing Ctrl+Shift+O will instruct

If you’re getting errors with the onClick(View v) Methods, its probably because you’re using an old JDK as the 1.5 one. In this case, remove the @Override line in order to fix it or change to JDK 1.6 (currently 1.6_03)

Screenshots (click to enlarge):

Login Screen 1 Login Screen Successful Login Screen Failed

Update: Small update for all of you who are not using Eclipse to develop their application, check out this Tutorial on how to compile Android Application without IDE.

Permanent link to this article: http://tseng-blog.nge-web.net/blog/2009/01/29/android-your-first-android-application/

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>