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.
First we create a new project by selecting the File menu -> New -> Android Project or right-clicking the Package Explorer -> New -> Android Project.
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.
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.
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.
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);
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();.
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.
@Override line in order to fix it or change to JDK 1.6 (currently 1.6_03)Screenshots (click to enlarge):
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.






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!
nice tutorial…..could you tell me how to connect this login ui with mysql database.
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
[...] - http://tseng-blog.nge-web.net/blog/2009/01/29/android-your-first-android-application/ [...]
thanks
[...] maken. Een simpele zoekterm op Google geeft helemaal veel opties, en binnen no-time liggen de bronnen voor het [...]
[...] We’ll use our good old LoginExample application, created in previous tutorial which can be found at Android: Your first Android Application. [...]
Thank you so much for this tutorial. It has helped me out a lot.
Hey,
Its nice tutorial for beginners.
Good Work, Keep Up.
-Aditya
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
Thanks for this! Great job and easy to follow!
Thanks Tseng, just starting my college project and needed a login view
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
Hey,
Surprise, I got the solution man
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
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!!!
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 :
What IDE/font is the code in? Looks very nice.
I am not getting the r.java file generated
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?
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
really good. Am a new one in android application development. i learned easily….Thankzzzzzzzzzzzzz
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.
Thanks lot Friend
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
Thank you so much….
It helped me a lot….