Tseng’s dev blog

A developers blog



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.

No related posts.







26 Responses to 'Android: Your first Android Application'

  1. giuseppe - January 30th, 2009 at 13:37

    I wish to point out this article.

    Android First Example in Java: Hello World
    http://programmaremobile.blogspot.com/2009/01/android-first-example-hello-world.html

    It expain the steps(from java code to running into emulator) to make the first hello world without eclipse.
    I hope it is welcome!

  2. vai - March 10th, 2009 at 18:07

    nice tutorial…..could you tell me how to connect this login ui with mysql database.

  3. Ajay - January 19th, 2010 at 10:36

    I have used “edittext” widget to take the input in xml.. but i am unable to insert the taken value into the database using insert stament. i have written the insert function as insert(string); so plz help me how to reteieve the edittext box value and store it as a string in some variable

  4. PoC3 – De stap naar een mobile App, what to do? - March 16th, 2010 at 21:21

    [...] -        http://tseng-blog.nge-web.net/blog/2009/01/29/android-your-first-android-application/ [...]

  5. hanu - March 19th, 2010 at 09:06

    thanks

  6. Databasegemak binnen je Android App - March 28th, 2010 at 20:26

    [...] maken. Een simpele zoekterm op Google geeft helemaal veel opties, en binnen no-time liggen de bronnen voor het [...]

  7. Implementing Listeners in your Android/Java application | Tseng's dev blog - April 29th, 2010 at 19:12

    [...] We’ll use our good old LoginExample application, created in previous tutorial which can be found at Android: Your first Android Application. [...]

  8. Marty - June 22nd, 2010 at 17:28

    Thank you so much for this tutorial. It has helped me out a lot.

  9. Name - July 1st, 2010 at 09:22

    Hey,
    Its nice tutorial for beginners.
    Good Work, Keep Up.
    -Aditya

  10. Alok Upadhyay - October 27th, 2010 at 06:42

    hi,
    i got some idea of event handling through your tutorial.so how to code for, when i click on btn.cancel an image got open…when i click on btn.save another image opened…….i am trying something like this ..
    i have three imagebuttons.i am able to veiw them and have done xml layouting successfully.Now what i want is that as user clicks on these image buttons new images should be open. i have all the images in my resource folder.
    three image buttons are as:
    1.seqIbtn(on clicking this, image named image_seq opened.)
    2.vidIbtn(On clicking this a video opens)
    3.infoIbtn(on clicking this, a image named image_info opened).code is as:

    package com.example.imageButton;

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

    import android.view.View;
    import android.widget.ImageButton;

    public class imageButton extends Activity {

    private static ImageButton seqIBtn;
    private static ImageButton vidIBtn;
    private static ImageButton infoIBtn;

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

    //Get pointers to the Views defined in main.xml
    seqIBtn = (ImageButton) findViewById(R.id.btnSequence);
    vidIBtn = (ImageButton) findViewById(R.id.btnVideo);
    infoIBtn = (ImageButton) findViewById(R.id.btnInfo);
    //seqIBtn.setOnClickListener(btnDoneOnClick);
    //vidIBtn.setOnClickListener(btnDoneOnClick);
    //infoIBtn.setOnClickListener(btnDoneOnClick);
    }

    // Create a button click listener for the Done button.
    private final ImageButton.OnClickListener btnDoneOnClick = new ImageButton.OnClickListener() {
    public void onClick(View v) {
    switch(v.getId()){

    case R.id.btnSequence:

    break;

    case R.id.btnVideo:

    break;
    }

    }
    };

    }

    please help i am not getting how to use onclicklistener and onclick() in such a way that on clicking different imagebutton different images get opened thanks

  11. George - November 18th, 2010 at 21:03

    Thanks for this! Great job and easy to follow!

  12. noID - November 18th, 2010 at 22:09

    Thanks Tseng, just starting my college project and needed a login view

  13. Jagan - January 12th, 2011 at 12:05

    Thanks for the information..
    I need help in this when we clicks the “Cancel” button application exits.. But in my application, I replaced the Cancel button with the Reset Button.. how to implement that functionality whether i have to display the login page again its not working.. I have clear the data in that edit text box.. how it will, i don’t know
    help me in this
    Thanks for reading

  14. Jagan - January 12th, 2011 at 12:19

    Hey,
    Surprise, I got the solution man

  15. aniket - February 8th, 2011 at 13:49

    your tutorial was very use full to me…
    just tell me one thing how to go next screen using this program. i mean intent code to start another activity in this above program…please help

  16. raghav - February 22nd, 2011 at 13:24

    really good!!! was searching for such a example!!! good job!! I am very new to android. i am working in android platform!!! pls post many more projects asap!!!

  17. Gerhard - May 2nd, 2011 at 10:27

    To go to next screen :

    Intent intent = new Intent(getApplicationContext(), NextScreenActivity.class);
    startActivity(intent);

    Don’t forget to register the activity in Android Manifest.xml :

  18. Jason - May 27th, 2011 at 08:58

    What IDE/font is the code in? Looks very nice.

  19. Toby - July 3rd, 2011 at 16:38

    I am not getting the r.java file generated :-(

  20. Toby - July 3rd, 2011 at 19:28

    Ah ok – setting autobuild on true in Eclipse helps ;-) However, what is missing in this tutorial is:

    - how do you start the thing? when I start it as an Android App (the project), I only get an empty page in the emulator

    - where do you “call” the LoginExample? Where is it referenced?

  21. Denise - September 12th, 2011 at 07:39

    Hi i have typed the codes in and when i click on the login button, nothing is shown. there isnt any error though. Please get back to me ASAP

  22. Mahi - September 29th, 2011 at 13:22

    really good. Am a new one in android application development. i learned easily….Thankzzzzzzzzzzzzz

  23. Bilety Autokarowe - November 21st, 2011 at 09:49

    Wow! This could be one particular of the most useful blogs We have ever arrive across on this subject. Actually Excellent. I’m also an expert in this topic therefore I can understand your hard work.

  24. Ra - December 22nd, 2011 at 11:06

    Thanks lot Friend

  25. J.Balaji - December 27th, 2011 at 10:27

    ur login form is very useful for me.please tel me how to merge my android app with this login form.thanks and regards J.Balaji

  26. born2kill - January 6th, 2012 at 17:43

    Thank you so much….
    It helped me a lot….


Leave a Reply