«

»

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/

33 comments

3 pings

Skip to comment form

  1. giuseppe

    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

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

  3. Ajay

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

    thanks

  5. Marty

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

  6. Name

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

  7. Alok Upadhyay

    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

  8. George

    Thanks for this! Great job and easy to follow!

  9. noID

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

  10. Jagan

    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

  11. Jagan

    Hey,
    Surprise, I got the solution man

  12. aniket

    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

  13. raghav

    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!!!

  14. Gerhard

    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 :

  15. Jason

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

  16. Toby

    I am not getting the r.java file generated 🙁

  17. Toby

    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?

  18. Denise

    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

  19. Mahi

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

  20. Bilety Autokarowe

    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.

  21. Ra

    Thanks lot Friend

  22. J.Balaji

    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

  23. born2kill

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

  24. Palle Mikkelsen

    Thanks.

    That cleared up a few questions.

  25. vano19

    hey, i finished you tutor and have some problem on OnClick(View)~ then the ide do self construct from pointing mouse to the problem and select the available methods~ and the idk add

    import android.view.View.OnClickListener;

    so, as i see on your tutor that:

    import android.view.View
    must be replace by the parameter above~

    hope can help the others~

  26. vano19

    my bad~ as i re-check it again, not replaced but add it alongside yours~

    hope can help others~

  27. ANKITA

    hey,
    i want code for scrabble game(logic part of game) for android.

  28. OPTIMIST

    I can’t make it run. It says unfortunately LoginExample has stopped… please help I am using eclipse latest version. Thanks

  29. ios developers

    Hello there! This post could not be written any better!
    Going through this article reminds me of my previous
    roommate! He constantly kept preaching about this. I most certainly will send
    this post to him. Pretty sure he’ll have a very good read. I appreciate you for sharing!

    my site – ios developers

  30. pick up artist season 1 download

    You made some good points there. I looked on the web for additional information
    about the issue and found most people will
    go along with your views on this site.

  31. Terra

    I see you share interesting stuff here, you can earn some extra money, your website has big
    potential, for the monetizing method, just type in google – K2 advices
    how to monetize a website

  32. Bennett

    I read a lot of interesting content here. Probably you spend a lot of time writing,
    i know how to save you a lot of time, there is an online
    tool that creates unique, google friendly articles in minutes, just type
    in google – laranitas free content source

  33. dayz standalone hacks

    Hurrah, that’s what I was searching for, what a information! existing here at this website, thanks admin oof this website.

  1. Databasegemak binnen je Android App

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

  2. Implementing Listeners in your Android/Java application | Tseng's dev blog

    […] We’ll use our good old LoginExample application, created in previous tutorial which can be found at 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>