What is an Android Activity?

In this post, we are going to discuss about ‘Activity’, for newbies the term ‘Activity’ might be looking like a jargon. Let us discuss it with a very simple example.

What is an Activity?

Activity is a Java code that supports a screen or UI. In other words, building block of the user interface is the activity.

Activity class is a pre-defined class in Android and every application which has UI must inherit it to create window.

Let us create a simple application which displays current time when you just tap the window. We will dissect the code to understand how the activity works.

Quick Links

Project Structure

  • Launch eclipse and create a new project: File >> New >> Android Project
  • Enter project name:  TimeNowApp, click next
  • Choose target device Android version
  • Enter package name: com.prgguru.android , click finish.

Code Listings

Layout creation:

Create simple layout with one button and button properties are given below:

 Button Control:

Assign android:layout_height and android:layout_width properties with value “match_parent” so the button will fill the whole layout of the application
Do not assign text property with any value since we want to display time in the place of text :android:text = “”

Create a button object right under the TimeNowAppActivity as a instance object;

Button btn;

We must tag the button we created in layout to the Activity in order to display it on the window. We often use ‘findViewById(resourceID)’ method to find the resource with the help of its ID.

The default ID of button we created is ‘button1’ and we need to pass it to the ‘findViewById(R.id.button1)’ method and assign it to the button object ‘btn’ to handle all button events.

btn = (Button) findViewById(R.id.button1);

R refers to Resource class, which has all resources like UI, media, images etc., associated with the application as inner classes. Just goto R.java [Project folder >> gen >> package >> R.java] and check it.

id refers to innder class of Resource class (R.java) which holds the IDs of the UI elements, media, images etc., It refers the elements as HEX codes. Open R.java and take a look at it.

button1 is the id of the button we created. It should be in main.xml as ‘android:id=”@+id/button1″‘. It is upto what name you want to give to the UI elements.

Let us create a separate method to update time when we tap the applicaition’s window:

//Method definition starts here with no return type
public void updateTime() { 
//Setting button text with current time
//java.util.Date() method is used to get the current time
btn.setText(new Date().toString());
}

Call updateTime() method in onCreate() method before handling the onClick() button event since we need to display the time when the application starts for first time.

Add Button listener code in onCreate() method:

//Onclick listener
btn.setOnClickListener(new View.OnClickListener() { 
//Onclick method
public void onClick(View v) { 
//Call updateTime() when button is clicked
updateTime(); 
}
});

Here is the entire class source code:

package com.prgguru.android;
import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class TimeNowAppActivity extends Activity {
/** Called when the activity is first created. */
Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
updateTime();
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
updateTime();
}
});
}
public void updateTime() {
btn.setText(new Date().toString());
}
}

[pglinkadssmall1]

Dissecting the activity code:

Your application must import all the necessary packages to facilitate your program to use pre-defined methods :

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

Activities are public classes, inheriting from the android.Activity base class.

public class TimeNowAppActivity extends Activity {

[pgsubscribe]
The onCreate() method is invoked when the activity is started.

The first thing we should do is chain upward to the superclass, so the stock Android activity initialization can be done.

In our implementation, we then set the layout of the application by passing layout xml to setContentView() method.

Then we are initializing the button object with the button id. To display time for first time, we call updateTime() method. To handle the button events, we set onclick listener and adding logic inside onClick() method. Here we are calling updateTime() method when the button is clicked.

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
updateTime();
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
updateTime();
}
});
}

updateTime() method is a user-defined method to update the time:

//Method definition starts here with no return type
public void updateTime() { 
//Setting button text with current time
//java.util.Date() method is used to get the current time
btn.setText(new Date().toString());
}

Build and run the application. Right click on the project >> Choose Run as >> Android Application >> Choose emulator or Android device.

Demo

Here is the output:

Tap the application window, time will be updated!

Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.

 

[pglinkadssmall]

Your feedback and comments are always welcome. :)

Suggested posts for further reading


[pgfeedback]
[pgwriteforus]

Related Articles

Author: Android Guru

Share This Post On
468 ad
  • R.Vinod Kumar

    Hi,

    Awesome work and updates. Hope you must have given a brief introduction to the architecture of android and also the components of Andorid which would quite interesting to know.

    • Sure Vinodh.. You can expect it in my future posts.
      Thanks for letting me know! :)

  • R.Vinod Kumar

    Hope Architecture alone since components covered in magic box. :)

  • deepu

    Best Example to understand activity… great

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares