Posts Tagged ‘Source code’

العربية: Android logo

A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. You can declare a layout in two ways:

  • Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.
  • Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and manipulate their properties) programmatically.

The Android framework gives you the flexibility to use either or both of these methods for declaring and managing your application’s UI. For example, you could declare your application’s default layouts in XML, including the screen elements that will appear in them and their properties. You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time.

  • The ADT Plugin for Eclipse offers a layout preview of your XML — with the XML file opened, select the Layout tab.
  • You should also try the Hierarchy Viewer tool, for debugging layouts — it reveals layout property values, draws wireframes with padding/margin indicators, and full rendered views while you debug on the emulator or device.
  • The layoutopt tool lets you quickly analyze your layouts and hierarchies for inefficiencies or other problems.

The advantage to declaring your UI in XML is that it enables you to better separate the presentation of your application from the code that controls its behavior. Your UI descriptions are external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile. For example, you can create XML layouts for different screen orientations, different device screen sizes, and different languages. Additionally, declaring the layout in XML makes it easier to visualize the structure of your UI, so it’s easier to debug problems. As such, this document focuses on teaching you how to declare your layout in XML. If you’re interested in instantiating View objects at runtime, refer to the ViewGroup and View class references.

In general, the XML vocabulary for declaring UI elements closely follows the structure and naming of the classes and methods, where element names correspond to class names and attribute names correspond to methods. In fact, the correspondence is often so direct that you can guess what XML attribute corresponds to a class method, or guess what class corresponds to a given xml element. However, note that not all vocabulary is identical. In some cases, there are slight naming differences. For example, the EditText element has a text attribute that corresponds to EditText.setText().

Tip: Learn more about different layout types in Common Layout Objects. There are also a collection of tutorials on building various layouts in the Hello Views tutorial guide.

Write the XML

Using Android’s XML vocabulary, you can quickly design UI layouts and the screen elements they contain, in the same way you create web pages in HTML — with a series of nested elements.

Each layout file must contain exactly one root element, which must be a View or ViewGroup object. Once you’ve defined the root element, you can add additional layout objects or widgets as child elements to gradually build a View hierarchy that defines your layout. For example, here’s an XML layout that uses a vertical LinearLayout to hold a TextView and a Button:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
              android:orientation="vertical" >
    <TextView android:id="@+id/text"
              android:text="Hello, I am a TextView" />
    <Button android:id="@+id/button"
            android:text="Hello, I am a Button" />

After you’ve declared your layout in XML, save the file with the .xml extension, in your Android project’s res/layout/ directory, so it will properly compile.

More information about the syntax for a layout XML file is available in the Layout Resources document.

Load the XML Resource

When you compile your application, each XML layout file is compiled into a View resource. You should load the layout resource from your application code, in your Activity.onCreate() callback implementation. Do so by calling setContentView(), passing it the reference to your layout resource in the form of: R.layout.layout_file_name For example, if your XML layout is saved as main_layout.xml, you would load it for your Activity like so:

public void onCreate(Bundle savedInstanceState) {

The onCreate() callback method in your Activity is called by the Android framework when your Activity is launched (see the discussion about lifecycles, in the Activities document).


Every View and ViewGroup object supports their own variety of XML attributes. Some attributes are specific to a View object (for example, TextView supports the textSize attribute), but these attributes are also inherited by any View objects that may extend this class. Some are common to all View objects, because they are inherited from the root View class (like the id attribute). And, other attributes are considered “layout parameters,” which are attributes that describe certain layout orientations of the View object, as defined by that object’s parent ViewGroup object.


Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute. This is an XML attribute common to all View objects (defined by the View class) and you will use it very often. The syntax for an ID, inside an XML tag is:


The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android package namespace, like so:


With the android package namespace in place, we’re now referencing an ID from the android.R resources class, rather than the local resources class.

In order to create views and reference them from the application, a common pattern is to:

  1. Define a view/widget in the layout file and assign it a unique ID:
    <Button android:id="@+id/my_button"
  2. Then create an instance of the view object and capture it from the layout (typically in the onCreate() method):
    Button myButton = (Button) findViewById(;

Defining IDs for view objects is important when creating a RelativeLayout. In a relative layout, sibling views can define their layout relative to another sibling view, which is referenced by the unique ID.

An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching (which may often be the entire tree, so it’s best to be completely unique when possible).

Layout Parameters

XML layout attributes named layout_something define layout parameters for the View that are appropriate for the ViewGroup in which it resides.

Every ViewGroup class implements a nested class that extends ViewGroup.LayoutParams. This subclass contains property types that define the size and position for each child view, as appropriate for the view group. As you can see in figure 1, the parent view group defines layout parameters for each child view (including the child view group).

Figure 1. Visualization of a view hierarchy with layout parameters associated with each view.

Note that every LayoutParams subclass has its own syntax for setting values. Each child element must define LayoutParams that are appropriate for its parent, though it may also define different LayoutParams for its own children.

All view groups include a width and height (layout_width and layout_height), and each view is required to define them. Many LayoutParams also include optional margins and borders.


You can specify width and height with exact measurements, though you probably won’t want to do this often. More often, you will use one of these constants to set the width or height:

  • wrap_content tells your view to size itself to the dimensions required by its content
  • fill_parent (renamed match_parent in API Level 8) tells your view to become as big as its parent view group will allow.

In general, specifying a layout width and height using absolute units such as pixels is not recommended. Instead, using relative measurements such as density-independent pixel units (dp), wrap_content, or fill_parent, is a better approach, because it helps ensure that your application will display properly across a variety of device screen sizes. The accepted measurement types are defined in the Available Resources document.

Layout Position

The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of left and top coordinates, and two dimensions, expressed as a width and a height. The unit for location and dimensions is the pixel.

It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.

In addition, several convenience methods are offered to avoid unnecessary computations, namely getRight() and getBottom(). These methods return the coordinates of the right and bottom edges of the rectangle representing the view. For instance, calling getRight() is similar to the following computation: getLeft() + getWidth().

Size, Padding and Margins

The size of a view is expressed with a width and a height. A view actually possess two pairs of width and height values.

The first pair is known as measured width and measured height. These dimensions define how big a view wants to be within its parent. The measured dimensions can be obtained by calling getMeasuredWidth() and getMeasuredHeight().

The second pair is simply known as width and height, or sometimes drawing width and drawing height. These dimensions define the actual size of the view on screen, at drawing time and after layout. These values may, but do not have to, be different from the measured width and height. The width and height can be obtained by calling getWidth() and getHeight().

To measure its dimensions, a view takes into account its padding. The padding is expressed in pixels for the left, top, right and bottom parts of the view. Padding can be used to offset the content of the view by a specific amount of pixels. For instance, a left padding of 2 will push the view’s content by 2 pixels to the right of the left edge. Padding can be set using the setPadding(int, int, int, int) method and queried by calling getPaddingLeft(), getPaddingTop(), getPaddingRight() and getPaddingBottom().

Even though a view can define a padding, it does not provide any support for margins. However, view groups provide such a support. Refer to ViewGroup and ViewGroup.MarginLayoutParams for further information.

For more information about dimensions, see Dimension Values.

Common Layouts

Each subclass of the ViewGroup class provides a unique way to display the views you nest within it. Below are some of the more common layout types that are built into the Android platform.

Note: Although you can nest one or more layouts within another layout to acheive your UI design, you should strive to keep your layout hierarchy as shallow as possible. Your layout draws faster if it has fewer nested layouts (a wide view hierarchy is better than a deep view hierarchy).

Linear Layout

A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen.

Relative Layout

Enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent).

Web View

Displays web pages.

Building Layouts with an Adapter

When the content for your layout is dynamic or not pre-determined, you can use a layout that subclasses AdapterView to populate the layout with views at runtime. A subclass of the AdapterView class uses an Adapter to bind data to its layout. The Adapter behaves as a middle-man between the data source and the AdapterView layout—the Adapter retreives the data (from a source such as an array or a database query) and converts each entry into a view that can be added into the AdapterView layout.

Common layouts backed by an adapter include:

List View

Displays a scrolling single column list.

Grid View

Displays a scrolling grid of columns and rows.

Filling an adapter view with data

You can populate an AdapterView such as ListView or GridView by binding the AdapterView instance to an Adapter, which retrieves data from an external source and creates a View that represents each data entry.

Android provides several subclasses of Adapter that are useful for retrieving different kinds of data and building views for an AdapterView. The two most common adapters are:

Use this adapter when your data source is an array. By default, ArrayAdapter creates a view for each array item by calling toString() on each item and placing the contents in a TextView.For example, if you have an array of strings you want to display in a ListView, initialize a new ArrayAdapter using a constructor to specify the layout for each string and the string array:

ArrayAdapter adapter = new ArrayAdapter<String>(this, 
        android.R.layout.simple_list_item_1, myStringArray);

The arguments for this constructor are:

  • Your app Context
  • The layout that contains a TextView for each string in the array
  • The string array

Then simply call setAdapter() on your ListView:

ListView listView = (ListView) findViewById(;

To customize the appearance of each item you can override the toString() method for the objects in your array. Or, to create a view for each item that’s something other than a TextView (for example, if you want an ImageView for each array item), extend the ArrayAdapter class and override getView() to return the type of view you want for each item.

Use this adapter when your data comes from a Cursor. When using SimpleCursorAdapter, you must specify a layout to use for each row in the Cursor and which columns in the Cursor should be inserted into which views of the layout. For example, if you want to create a list of people’s names and phone numbers, you can perform a query that returns a Cursor containing a row for each person and columns for the names and numbers. You then create a string array specifying which columns from the Cursor you want in the layout for each result and an integer array specifying the corresponding views that each column should be placed:

String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME, 
int[] toViews = {,};

When you instantiate the SimpleCursorAdapter, pass the layout to use for each result, the Cursor containing the results, and these two arrays:

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
        R.layout.person_name_and_number, cursor, fromColumns, toViews, 0);
ListView listView = getListView();

The SimpleCursorAdapter then creates a view for each row in the Cursor using the provided layout by inserting each fromColumns item into the corresponding toViews view.


If, during the course of your application’s life, you change the underlying data that is read by your adapter, you should call notifyDataSetChanged(). This will notify the attached view that the data has been changed and it should refresh itself.

Handling click events

You can respond to click events on each item in an AdapterView by implementing the AdapterView.OnItemClickListener interface. For example:

// Create a message handling object as an anonymous class.
private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View v, int position, long id) {
        // Do something in response to the click

Enhanced by Zemanta

How to compile C programsIn many of my previous posts especially in the VIRUS CREATION section, I have used C as the programming language for writing the programs. If you’re new to C programming and find it difficult to compile the C source codes then this post is for you.

Here is a step-by-step procedure to install Borland C++ compiler 5.5 on your PC and compile the C programs.

How to Install Borland C++ compiler?

Follow the below steps to install Borland C++ compiler 5.5 on your PC:

  1. Download Borland C++ compiler 5.5 (for Windows platform) from the following link:
  2. After you download, run the file C++5.51.exe. The default installation path would be:

How to configure Borland C++ compiler?

Here is a step-by-step instruction on how to configure the compiler:

  1. After you install Borland C++ compier, create two new Text Documents.
  2. Open the first New Text Document.txt file and add the following two lines into it:



    Save changes and close the file. Now rename the file from New Text Document.txt to bcc32.cfg.

  3. Open the second New Text Document (2).txt file and add the following line into it:

    Save changes and close the file. Rename the file from New Text Document (2).txt to ilink32.cfg.

  4. Now copy the two files bcc32.cfg and ilink32.cfg, navigate to C:\Borland\BCC55\Bin and paste them.

How to Compile the C Source Code (.C files)?

Here is a detailed instruction on how to compile C source codes:

  1. You need to place the .C (example.c) file to be compiled in the following location:
  1. Now go to the command prompt (Start->Run->type cmd->Enter)
  2. Make the following path as the present working directory (use the CD command):
  1. To compile the file (example.c) use the following command:
bcc32 example.c
  1. Now if there exists no error in the source code, you’ll get a compiled executable module (example.exe) in the same location (C:\Borland\BCC55\Bin).
  2. Now you have successfully compiled the source code into an executable file(.exe file).
NOTE: The above tutorial assumes that you’ve installed the compiler onto the C: drive (by default).

The official online color is: #A4C639 . 한국어: 공...

I think it’s very often we want to explore the existing projects source code but again sometime it may not be  available. Personally I love to dig on existing project to know how people write their codes.

Suddenly I thought, if there is any apk to java source decompiler, it would be a nice thing.  You probably know, android runs on dalvik virtual machine, so when we compile android java code, its compile to dex( dalvik executable). So I search a lot to find a way how to convert dex to jar ,and I know already how to decompile jar file to java source code.

At last I found the way out.

Here is the way-

You will need-

  1. Eclipse IDE
  2. Java Runtime (of course)
  3. JDGUI or JD Eclipse plugin   [url for eclipse Plugin visit ) ]
  4. DexToJar (get them from here:

And now follow the steps

Step 1:  Create a java project, name it DexToJava.

Create a java project

Step 2: Create a folder and name it libs. Paste all jars file in the libs folder after extracting dex2jar- . Go to build path. Add all the jars in the build path.

Step 3: You are almost done.  Get an apk file and paste it in your project. For me it is facebook.apk.

Step 4: right click on project and select run as.  Set main class: com.googlecode.dex2jar.v3.Main

Step 5: Set Argument facebook.apk and now click on apply and run it.

Step 6: after completing the job, you will find on console:

Step 7: now refresh the project, and you will find facebook_dex2jar.jar. And you know already how to get java source from jar. Use JD-GUI.

From jar file extracting  code ….. use

That all.

I think you enjoy it.

Android Robot. Français : le logo d'android 日本...

In this tutorial, you will learn how to use Eclipse to create an Android JUnit Test Project, create automated unit tests and run them under a variety of conditions.

Before You Begin

The authors are assuming the reader has some basic knowledge of Android and have all of the tools such as Eclipse and the Android SDK installed and working. The examples given here are engineered to show how the Android JUnit framework can be used to test Android applications. Specifically, this tutorial will show you how to test aspects of an Activity and identify program errors. These errors are determined, but not addressed, as part of this tutorial.

Note: The code for the SimpleCalc application is available on Google Code as well as from the above link.

Step 1: Review the SimpleCalc Application

First, let’s take a few moments to look over the SimpleCalc application. It’s a very simple application with just one screen. The screen has two simple functions: it allows the user to input two values, adds or multiplies these values together and displays the result as shown below.

Junit Testing The SimpleCalc application

Step 2: Review the SimpleCalc Screen Layout

The SimpleCalc application has just one screen, so we have only one layout resource file called /res/layout/main.xml.

Here is a listing of the main.xml layout resource:
  1. <?xml version=”1.0″ encoding=”utf-8″?>
  2. <LinearLayout xmlns:android=”;
  3.     android:orientation=”vertical” android:layout_width=”fill_parent”
  4.     android:layout_height=”fill_parent”>
  5.     <TextView android:layout_width=”fill_parent”
  6.         android:layout_height=”wrap_content” android:text=”@string/hello”
  7.         android:gravity=”center_horizontal” android:textSize=”48px”
  8.         android:padding=”12px” />
  9.     <EditText android:layout_height=”wrap_content” android:id=”@+id/value1″
  10.         android:hint=”@string/hint1″ android:inputType=”numberDecimal”
  11.         android:layout_width=”fill_parent” android:textSize=”48px”></EditText>
  12.     <EditText android:layout_height=”wrap_content” android:id=”@+id/value2″
  13.         android:hint=”@string/hint2″ android:inputType=”numberDecimal”
  14.         android:layout_width=”fill_parent” android:textSize=”48px”></EditText>
  15.     <FrameLayout android:id=”@+id/FrameLayout01″
  16.         android:layout_width=”wrap_content” android:layout_height=”wrap_content”
  17.         android:padding=”12px” android:background=”#ff0000″>
  18.         <LinearLayout android:id=”@+id/LinearLayout02″
  19.             android:layout_width=”wrap_content” android:layout_height=”wrap_content”
  20.             android:orientation=”horizontal” android:background=”#000000″
  21.             android:padding=”4px”>
  22.             <TextView android:layout_width=”wrap_content”
  23.                 android:layout_height=”wrap_content” android:text=”@string/resultLabel”
  24.                 android:textSize=”48px” android:id=”@+id/resultLabel”></TextView>
  25.             <TextView android:layout_width=”wrap_content”
  26.                 android:layout_height=”wrap_content” android:id=”@+id/result”
  27.                 android:textSize=”48px” android:textStyle=”bold”
  28.                 android:layout_marginLeft=”16px”></TextView>
  29.         </LinearLayout>
  30.     </FrameLayout>
  31.     <LinearLayout android:id=”@+id/LinearLayout03″
  32.         android:layout_height=”wrap_content” android:layout_width=”fill_parent”>
  33.         <Button android:layout_height=”wrap_content” android:id=”@+id/addValues”
  34.             android:text=”@string/add” android:textSize=”32px”
  35.             android:layout_width=”wrap_content”></Button>
  36.         <Button android:layout_height=”wrap_content” android:id=”@+id/multiplyValues”
  37.             android:text=”@string/multiply” android:textSize=”32px”
  38.             android:layout_width=”wrap_content”></Button>
  39.     </LinearLayout>
  40. </LinearLayout>

This layout is fairly straightforward. The entire content of the screen is stored within a LinearLayout, allowing the controls to display one after another vertically. Within this parent layout, we have the following controls:

  • A TextView control displaying the header “Unit Testing Sample.”
  • Two EditText controls to collect user input in the form of two numbers.
  • A FrameLayout control which contains a horizontal LinearLayout with the result label TextView and resulting sum or product TextView. The FrameLayout displays a red border around these controls, highlighting the result.
  • Finally, another horizontal LinearLayout with two child controls: a Button control for addition and a Button control for multiplication.

This layout is designed to look right in the Android Layout Designer when the Nexus One option (which has a screen size of 800×480) is chosen in both portrait and landscape modes. You’ll soon see that this is not a bullet-proof way of designing layouts. As with the code you’ll see in the next step, it isn’t designed to work perfectly.

Step 3: Review the SimpleCalc Activity

The SimpleCalc application has just one screen, so we have only one Activity as well: The class controls the behavior of the one screen, whose user interface is dictated by the main.xml layout.

Here is a listing of the class:

  1. package com.mamlambo.article.simplecalc;
  2. import;
  3. import android.os.Bundle;
  4. import android.util.Log;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;
  8. import android.widget.EditText;
  9. import android.widget.TextView;
  10. public class MainActivity extends Activity {
  11.    /** Called when the activity is first created. */
  12.    @Override
  13.    public void onCreate(Bundle savedInstanceState) {
  14.        final String LOG_TAG = “MainScreen”;
  15.        super.onCreate(savedInstanceState);
  16.        setContentView(R.layout.main);
  17.        final EditText value1 = (EditText) findViewById(;
  18.        final EditText value2 = (EditText) findViewById(;
  19.        final TextView result = (TextView) findViewById(;
  20.        Button addButton = (Button) findViewById(;
  21.        addButton.setOnClickListener(new OnClickListener() {
  22.            public void onClick(View v) {
  23.                try {
  24.                    int val1 = Integer.parseInt(value1.getText().toString());
  25.                    int val2 = Integer.parseInt(value2.getText().toString());
  26.                    Integer answer = val1 + val2;
  27.                    result.setText(answer.toString());
  28.                } catch (Exception e) {
  29.                    Log.e(LOG_TAG, “Failed to add numbers”, e);
  30.                }
  31.            }
  32.        });
  33.        Button multiplyButton = (Button) findViewById(;
  34.        multiplyButton.setOnClickListener(new OnClickListener() {
  35.            public void onClick(View v) {
  36.                try {
  37.                    int val1 = Integer.parseInt(value1.getText().toString());
  38.                    int val2 = Integer.parseInt(value2.getText().toString());
  39.                    Integer answer = val1 * val2;
  40.                    result.setText(answer.toString());
  41.                } catch (Exception e) {
  42.                    Log.e(LOG_TAG, “Failed to multiply numbers”, e);
  43.                }
  44.            }
  45.        });
  46.    }
  47. }
As you can see, the Java for this class is quite straightforward. It simply implements onClick() handlers for both the addition and multiplication Button controls.

When a Button is pressed, the Activity retrieves the values stored in the two EditText controls, calculates the result, and displays it in the TextView control called

Note: There are bugs in this code! These bugs have been designed specifically to illustrate unit testing.

Step 4: Creating an Android Test Project

You can add a test project to any Android project in two ways. You can add a test project while creating a new Android project with the Android Project Wizard or you can add a test project to an existing Android project. (The steps are basically the same.)

For this example, we have an existing project. To add a test project to the SimpleCalc project in Eclipse, take the following steps:

From the Project Explorer, choose the Android project you wish to add a test project to. Right-click on the project and choose Android Tools->New Test Project…

Junit Testing, Creating a Test Project

Step 5: Configuring the Android Test Project

Now you need to configure the test project settings, including the test project name, file location, Android project to test and build target (SDK version).

For this example, we can use the following settings:

  • Test project names generally end in “Test”, so let’s name this test project SimpleCalcTest
  • The project location can be wherever you normally store source files on your hard drive.
  • Choose the Android project to test: SimpleCalc
  • The appropriate build target will be selected automatically once you select the project to test. In this case, since the Android project is built for Android 2.1 + Google APIs (API Level 7), it makes sense to use the same build target for the test project.
  • It makes sense to name the test project accordingly: SimpleCalcTest, with the appropriate package name suffix simplecalc.test.
Configuring the project test

Hit Finish.

Step 6: Review the SimpleCalcTest Project

The SimpleCalcTest project is an Android project. You will notice that it has all the normal things you’d expect of an Android project, including a Manifest file and resources.

Junit Testing SimpleCalcTest Project Files

Step 7: Determine Unit Tests for the SimpleCalc Application

Now that you have a test project configured for the SimpleCalc application, it makes sense to determine some reasonable unit tests for the application.

Many software methodologies these days work compatibly with unit testing. Unit tests can greatly increase the stability and quality of your application and reduce testing costs. Unit tests come in many forms.

Unit tests can:

  • Improve testing coverage
  • Test application assumptions
  • Validate application functionality

Unit tests can be used to test core functionality, such as whether or not the SimpleCalc math is being performed correctly. They can also be used to verify if the user interface is displaying correctly. Now let’s look at some specific test cases.

Step 8: Create Your First Test Case

To create your first test case, right-click on the simplecalc.test package and choose New->JUnit Test Case.

Configuring test case settings.

Step 9: Configure Your First Test Case

Now you need to configure the test case settings.

For this example, we can use the following settings:

  • Both JUnit 3 and 4 are supported. We’ll use the default JUnit 3 here.
  • The source folder should be the location of the SimpleCalcTest project files.
  • The package should be the package name of the SimpleCalcTest project.
  • In this case, we will name the test case MathValidation.
  • For the SuperClass, choose “android.test.ActivityInstrumentationTestCase2.” This is the test case you use for testing activities.
  • Check the boxes to add method stubs for setUp() and constructor.
junit Testing, Configuring test case settings.

Hit Finish. (You can safely ignore the warning saying, “Superclass does not exist.”)

Step 10: Review the MathValidation Test Case

The test case source file is then created.

The lifecycle of a test case is basically this: construction, setUp(), tests run, tearDown(), and destruction. The setUp() method is used to do any general initialization used by all of specific tests. Each test to be run in the test case is implemented as its own method, where the method name begins with “test”. The tearDown() method is then used to uninitialize any resources acquired by the setUp() method.

  1. package com.mamlambo.article.simplecalc.test;
  2. import android.test.ActivityInstrumentationTestCase2;
  3. public class MathValidation extends
  4.        ActivityInstrumentationTestCase2<MainActivity> {
  5.    public MathValidation(String name) {
  6.        super(name);
  7.    }
  8.    protected void setUp() throws Exception {
  9.        super.setUp();
  10.    }
  11. }

Now it’s time to implement the MathValidation Test Case

Step 11: Modify the MathValidation Class Constructor

First, modify the MathValidation class constructor. This constructor ties configures the internals of the Android test superclass we’re using.

  1. public MathValidation() {
  2.        super(“com.mamlambo.article.simplecalc”, MainActivity.class);
  3. }

Step 12: Implement the MathValidation setUp() method

Now you need to gather the data required for validating the SimpleCalc math calculations. Begin by implementing the setUp() method. You can retrieve the Activity being tested using the getActivity() method as follows:

  1. MainActivity mainActivity = getActivity();

Next, you need to retrieve an instance of the TextView control called This is the control that will hold the resulting sum or product from the math calculations used by the application.

The full updated code listing ( with these modifications is shown below:

  1. package com.mamlambo.article.simplecalc.test;
  2. import android.test.ActivityInstrumentationTestCase2;
  3. import android.widget.TextView;
  4. import com.mamlambo.article.simplecalc.MainActivity;
  5. import com.mamlambo.article.simplecalc.R;
  6. public class MathValidation extends ActivityInstrumentationTestCase2<MainActivity> {
  7.    private TextView result;
  8.    public MathValidation() {
  9.        super (“com.mamlambo.article.simplecalc”, MainActivity.class);
  10.    }
  11.    @Override
  12.    protected void setUp() throws Exception {
  13.        super.setUp();
  14.        MainActivity mainActivity = getActivity();
  15.        result = (TextView) mainActivity.findViewById(;
  16.    }
  17. }

Step 13: Consider Tests for the SimpleCalc Application

Now that everything is set up, what tests do you want to perform? Let’s begin by checking the math used by the SimpleCalc application. Specifically, let’s check that the numbers are retrieved correctly, as well as added and multiplied correctly. Did we set the right types for our number values? Are we retrieving and performing mathematical calculations using the correct types?

To answer these questions, we must add some testing code to the MathValidation class. Each specific test will have it’s own method beginning with “test” – the “test” method name prefix is case sensitive! This naming scheme is how JUnit determines what methods to run.

Step 14: Implement a Method to Test SimpleCalc’s Addition

Let’s begin by testing the addition calculation of SimpleCalc. To do this, add a method called testAddValues() to the MathValidation class.

This test will enter two numbers (24 and 74) into the screen and press Enter, which acts as a click on the first Button control which is in focus. Then it will retrieve the sum displayed by the application in the result TextView control and test to see if the result is the expected one (98).

To supply the EditText controls with two numbers to sum, use the sendKeys() method. This method mimics how keys are sent to Android applications. If you use the setText() method of the EditText control to set the text in each control, then you are bypassing the validation of the numeric entry that user’s would encounter. This method of providing key strokes assumes that the focus starts on the first control and that using the Enter key goes to the next one (you’ll see that the enter key is sent at the end of each number). If neither of those assumptions is true, the test will also fail. This is not a bad thing, but it might be failing for the wrong reasons (e.g. focus or layout issues, rather than math issues).

Finally, you use the assertTrue() method to compare the actual result displayed on the screen to the expected result. ). We compare against a string, since the result is displayed as a string. This way, we can also make sure we don’t duplicate any math or type errors in the application logic within the test framework.
Here is the full listing of the testAddValues() method:

  1. private static final String NUMBER_24 = “2 4 ENTER “;
  2. private static final String NUMBER_74 = “7 4 ENTER “;
  3. private static final String ADD_RESULT = “98”;
  4. public void testAddValues() {
  5.    sendKeys(NUMBER_24);
  6.    // now on value2 entry
  7.    sendKeys(NUMBER_74);
  8.    // now on Add button
  9.    sendKeys(“ENTER”);
  10.    // get result
  11.    String mathResult = result.getText().toString();
  12.    assertTrue(“Add result should be 98”, mathResult.equals(ADD_RESULT));
  13. }

Congratulations! You’ve created your first test!

Step 15: Enhancing the Tests for Addition

Now let’s add a few more tests to make sure all different types of numbers can be added, resulting in the display of the proper sum.

Because the activity is launched for each test, you do not need to clear the values or anything like that between tests. You also do not need to change the focus within the form, since it begins at value1. Therefore, you can simplify tests by concatenating key presses together in a single sendKeys() method call, like such:

  1. sendKeys(NUMBER_24 + NUMBER_74 + “ENTER”);

For example, here is the code for the testAddDecimalValues() method, which tests the addition of a decimal value 5.5 with the number 74, which should result in 79.5:

  1. public void testAddDecimalValues() {
  2.        sendKeys(NUMBER_5_DOT_5 + NUMBER_74 + “ENTER”);
  3.        String mathResult = result.getText().toString();
  4.        assertTrue(“Add result should be ” + ADD_DECIMAL_RESULT + ” but was “
  5.                + mathResult, mathResult.equals(ADD_DECIMAL_RESULT));
  6.  }

Similarly, you can perform a test of adding a negative number -22 to the number 74, which should result in a sum of 52. This test is implemented in the testSubtractValues() method, as follows:

  1. public void testAddDecimalValues() {
  2.        sendKeys(NUMBER_5_DOT_5 + NUMBER_74 + “ENTER”);
  3.        String mathResult = result.getText().toString();
  4.        assertTrue(“Add result should be ” + ADD_DECIMAL_RESULT + ” but was “
  5.                + mathResult, mathResult.equals(ADD_DECIMAL_RESULT));
  6.    }

Step 16: Implement a Method to Test SimpleCalc’s Multiplication

It should be quite straightforward to implement a similar test for SimpleCalc’s multiplication called testMuliplyValues().

The only tricky part is that the Multiply Button control is not in focus when we’re done entering the numbers (instead, the Add Button is).
You might think to just call the requestFocus() method on the multiply button. Unfortunately, this won’t work because requestFocus() has to be run on the UI thread in Android. Running methods on the UI Thread can be done as part of a test case, but it’s done asynchronously so you can’t guarantee when it will be complete.

Instead, we’ll again use the sendKeys() method. Since we defined the Multiply Button to always display to the right of the Add Button, we can just send the “DPAD_RIGHT” key followed by “ENTER” to click the Multiply Button.

  1. public void testMultiplyValues() {
  2.    sendKeys(NUMBER_24+NUMBER_74+ ” DPAD_RIGHT ENTER”);
  3.    String mathResult = result.getText().toString();
  4.    assertTrue(“Multiply result should be ” + MULTIPLY_RESULT + ” but was “
  5.            + mathResult, mathResult.equals(MULTIPLY_RESULT));
  6. }

As an exercise, you might try adding more multiplication tests with various sizes of numbers. Try to engineer a test that might fail with the existing code. Can you guess if each test will be successful or not? (Hint: Look at the type of the variable that the string is being converted to.)

Step 17: Running Unit Tests with the Android Emulator or Device

Unit test frameworks such as the one you’re building are Android applications like any other. They must be installed on the emulator or device you wish to test, along with the application to be tested (in this case, SimpleCalc).

To run the unit tests you have created so far from Eclipse, choose the Debug drop down, then Debug As, then Android JUnit Test. Make sure the file you just created is the active file (shown in the window) as that is the test case that will be launched.

junit testing, Debugging JUnit Test

Step 18: Examining the Test Results

The tests may take some time to complete, especially if the emulator was not already running. When the tests have completed, you should see results similar to those shown here:

Junit Testing Examining the Test Results

You’ll notice that all four of the tests you’ve just created run. Two of them are successful, while two of them have failed. Do you know why they’ve failed? (Fixing these calculation bugs is left as a learning exercise for the reader.)

Besides successful tests and failed tests, errors are also shown. A failure is when a tested for assertion fails. An error, on the other hand, is a thrown exception. Errors can either be untested for edge cases or simply mistakes in the testing code. If you have errors, check your testing code carefully to make sure it is working correctly.

Step 19: Create a Test Case for Screen Display Testing

Unit tests need not be limited to validating core functionality such as the addition and multiplication of values. Tests can also validate whether or not a screen layout is displayed properly.

For example, you might want to validate that all of the layout controls display properly on all target screens. The SimpleCalc’s screen was designed in the layout designer in Eclipse for an 800×480 screen in either landscape or portrait mode, but will it work on other screen sizes and devices? Were we then too specific in our design? Automated testing can tell us the answer to this question very quickly.

To create another test case, right-click on the SimpleCalc.Test package and choose New->JUnit Test Case. Call this new test LayoutTests. Configure this test case much as you did the MathValidation class in Step 8.

Junit testing, Create a Test Case for Screen Display Testing.

Hit Finish.

Step 20: Review and Update the LayoutTests Test Case

The test case source file is then created. Modify the class to look like the code listing below, modifying the constructor, retrieving the Button controls and the layout as a whole:

  1. package com.mamlambo.article.simplecalc.test;
  2. import android.test.ActivityInstrumentationTestCase2;
  3. import android.view.View;
  4. import android.widget.Button;
  5. import com.mamlambo.article.simplecalc.MainActivity;
  6. import com.mamlambo.article.simplecalc.R;
  7. public class LayoutTests extends ActivityInstrumentationTestCase2<MainActivity> {
  8.    private Button addValues;
  9.    private Button multiplyValues;
  10.    private View mainLayout;
  11.    public LayoutTests() {
  12.        super(“com.mamlambo.article.simplecalc”, MainActivity.class);
  13.    }
  14.    protected void setUp() throws Exception {
  15.        super.setUp();
  16.        MainActivity mainActivity = getActivity();
  17.        addValues = (Button) mainActivity.findViewById(;
  18.        multiplyValues = (Button) mainActivity
  19.                .findViewById(;
  20.        mainLayout = (View) mainActivity.findViewById(;
  21.    }
  22. }
Now let’s implement some specific tests for LayoutTests.

Step 20: Consider Layout Tests for the SimpleCalc Application
Now that everything is set up, what tests do you want to perform? One common bug in application design is for controls not to display properly in all screen sizes and orientations. Therefore, it makes sense to try to build a test case to verify the location of certain controls. You can then add other checks to make sure other View controls display and behave appropriately.

Step 21: Implement a Method to Test Button Display

Let’s begin by testing that the Add Button control of the SimpleCalc screen is visible. To do this, add a method called testAddButtonOnScreen() to the LayoutTests class.

This test checks to see if the Add Button control is displayed within the visible rectangle representing the overall screen size.

To implement the testAddButtonOnScreen() method, you must first determine the screen size. There are a number of ways to do this. One simple way is to retrieve the View that represents the entire screen layout and use the getWidth() and getHeight() methods. Doing this also takes in to account any screen real estate being used by other items, such as the title bar or information bar that are often at the top of an Android screen.

Determining whether or not the Add Button control is drawn within those bounds is as simple as comparing the layout bounds to the bounds of the drawing rectangle for the Add Button control.

Here is the full listing of the testAddButtonOnScreen() method:

  1. public void testAddButtonOnScreen() {
  2.    int fullWidth = mainLayout.getWidth();
  3.    int fullHeight = mainLayout.getHeight();
  4.    int[] mainLayoutLocation = new int[2];
  5.    mainLayout.getLocationOnScreen(mainLayoutLocation);
  6.    int[] viewLocation = new int[2];
  7.    addValues.getLocationOnScreen(viewLocation);
  8.    Rect outRect = new Rect();
  9.    addValues.getDrawingRect(outRect);
  10.    assertTrue(“Add button off the right of the screen”, fullWidth
  11.            + mainLayoutLocation[0] > outRect.width() + viewLocation[0]);
  12.    assertTrue(“Add button off the bottom of the screen”, fullHeight
  13.            + mainLayoutLocation[1] > outRect.height() + viewLocation[1]);
  14. }

At this point, you can see how you could also test the display of the Multiply Button, or the Result text, or any other control on the SimpleCalc screen.

Step 22: Running the LayoutTests Test Case

In order for layout testing to provide useful results, we can’t just run the test once. Instead, the tests must be run on multiple emulator configurations and screen orientations. This is different from the logic tests of above where a messy layout or a layout that doesn’t match the design pattern doesn’t necessarily impede functionality.

For example, if you create emulator configurations (using AVDs) for the following configurations, the LayoutTests test case will yield the following results:

  1. 480×800, portrait mode (will pass)
  2. 800×480, landscape mode (will fail)
  3. 320×480, portrait mode (will fail)
  4. 480×320, landscape (will fail)
  5. 480×854, portrait mode (will pass)
  6. 854×480, landscape mode (will fail)

 Can you figure out why it fails in all landscape modes, but draws fine in the creator for the landscape mode (#2 above)?

Can you figure out why it fails in all landscape modes, but draws fine in the creator for the landscape mode (#2 above)?

Hint: What’s shown on the screen when the application actually runs (see the figure below)?

JUnit Testing Sample

Step 23: Where to Go From Here

Now that you have some tests in place—some of which pass and some of which fail—you can imagine how unit testing can improve the quality of your application.

The more thorough you are with your unit testing coverage, the better. You’ve seen how unit testing can uncover bugs in code and layout designs. The next step would be to identify the failure points and fix those bugs. Once you’ve fixed the bugs, you should re-run the unit tests to ensure that they pass in all test cases.


In this tutorial, you learned how to create unit tests using the Android JUnit framework for your Android projects. You also learned how to create different kinds of unit tests to test a variety of application features, including underlying program functions as well as display characteristics.