Getting Started With Android Development

By | August 3, 2014

Introduction

In this article, we will be creating a simple “Hello World” Android application. We will use the default template that Eclipse provides while creating a new android app and we will also examine the files that are created. I will give a brief overview of each step and you will get a fair idea on how you can start developing applications. To develop applications for Android, you will require the Android SDK along with the platform tools and a development environment. In this tutorial, i will be creating the application using the Eclipse IDE. To download the tools and configure your development environment, visit the Android Developer site and download the ADT bundle. Once you have all the tools installed, you are ready to proceed further. You will also need to have a basic knowledge of Java and have the latest Java SDK installed on your machine.

Creating the Project

Start the Eclipse IDE. Click on File –> New –> Project. In the window that opens as shown below, expand the Android Folder and select “Android Application Project” and click Next

In the New Android Application Dialog that appears next where we set the details about our application. Fill in the information as shown below and click Next

Here is a brief info on what the different fields means

Application Name: This will be the name of the Android Application and the same will appear on the Playstore.

Project Name: The name of the project that will appear in the Eclipse workspace. You will notice that as you type your Application Name, the Project Name is filled automatically. Typically you keep the same name for Project and Application but it is not mandatory

Package Name: This specifies the namespace of your application and it has to be unique as no two application having the same namespace can be deployed on the Playstore. Generally the practice is to use your reverse domain name as the package name. For this example, we will just leave it as default

Minimum Required SDK: It specifies the lowest Android version that our application support. We keep it as API 8 as there are still a lot of devices which run on older Android versions.

Target SDK: This specifies the highest Android API against which you have tested your application. It is best practice to always test your application against the latest version to avoid any compatibility issues.

Compile With: This is the version against which the application will be compiled. You should always compile your application against the latest Android version available.

Theme: It specifies the style that will be applied to the app. Leave it to default.

In the Configure Project screen that appears, leave the default options selected as shown below and click Next

Here we specify whether we want to create a custom launch icon and an activity. We also specify the path where our project files will be stored.

The next screen lets you create a custom launch icon for the app. You can use a custom image also. It also generates icons for all the different screen densities. For now lets leave the default and click Next

In the Create Activity Screen, we will select “Blank Activity” and click Next

An Activity is the UI layer of the android application. It contains all your UI elements and provides a front end through which users can interact with the application. Typically, an Android application consists of multiple activities.

In the Next screen, we provide details about the blank activity like the Name and layout name. Keep the default and click “Finish”

Once you click on Finish, Eclipse will create the project and the same will be loaded into the workspace.  Shown below is how our Eclipse will look once the project has been loaded. In the left hand side, we have the “Package Explorer” which can be used to view and navigate between different files/folders of our application.

Lets take a closer look at the Folder structure of our Android application and i will explain what are the different types of folders and files.

  • src : This folder contains the source code of our project. It contains a file called MainActivity.java which was created when we created a new activity through the wizard.
  • gen : This folder contains the generated files which are generated
  • assets : Currently this folder is empty but you can use it to place your external assets like database, sound files etc
  • libs : This contains any libraries or any external libraries used by your project
  • res : This contains the resources that are used by the application. It also contains various different folders. Lets take a look at them
    • drawable : A drawable is something that can be drawn on the screen through the activity. This include icons, images, animations etc. We have 5 different folders in our project which represent different screen densities : low, medium, high, extra high, extra extra high. You will notice that there is a file called “ic_launcher.png” present in the folders. This is the custom launch icon which we created while creating the project. Using the folders, you can provide different custom graphics which will be displayed based on the type of device in which your application is run. The graphics in your “drawable-ldpi” folder should be optimized for Low resolution devices which the graphics in “drawable-xxhdpi” should be optimized for HD phones and tablets.
    • layout : This folder contains the layout XML files for our activity. The UI components in the Activity are defined in a XML file. For each activity in the project, there will be a corresponding layout file.
    • menu : It contains the XML files which defines the menu structure of the activity
    • values : These folders contain the file “strings.xml”, “dimen.xml”, “styles.xml” and these are used to store the constant value for our string, dimensions and styles. Putting all our constants in these files allows them to be accessed from anywhere. It can also help a lot during localization.

UI Layout in Android

All the layout in Android is defined in the XML file. Lets open “activity_main.xml” files inside the layout folder and have a look at how it is designed.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

The first tag is the <RelativeLayout> tag which defines the layout container which will hold the UI components of the activity. In the RelativeLayout, the UI elements are placed relative to one another. There are different type of layout like LinearLayout, TableLayout that can also be used. The tag also contains other elements like “android:layout_width”, “android:layout_height” etc. which are used to specify the width and height of the layout. There are different feature like paddingLeft, paddingBottom which can also be specified.

The “match_parent” value for width and height allows the Relative Layout to expand and occupy the entire screen of the device. Inside the layout we have a <TextView> tag which is similar to the label control we have in other languages. This control is used to display the “Hello World” text in the screen. For displaying the text in the TextView, we use the “android:text=”@string/hello_world”. The “@string/hello_world” specifies that we are picking a value from the “strings.xml” file containing the key “hello_world” instead of hard coding the value here. If you open strings.xml inside the values folder, it will show below code

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Hello World App</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>

</resources>

In our TextView, the text “@string/hello_world” will get replaced by the “Hello world!” value which is specified in the strings.xml file. To change the value, you can update the strings.xml file and it will take effect in the UI. Similarly we have specified the using the “@dimen/activity_vertical_margin” and other constants which are specified in dimen.xml file.

The R File

Right Click the “HelloWorldApp” project in the Package Explorer in Eclipse and click “Build Project”. After the project has built successfully, you will find a R.java file inside the gen folder –> com.example.helloworldapp namespace. Double Click the file to open it and it will contain the below code

public final class R {
    public static final class attr {
    }
    public static final class dimen {
        /**  Default screen margins, per the Android Design guidelines.

         Customize dimensions originally defined in res/values/dimens.xml (such as
         screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.

         */
        public static final int activity_horizontal_margin=0x7f040000;
        public static final int activity_vertical_margin=0x7f040001;
    }
    public static final class drawable {
        public static final int ic_launcher=0x7f020000;
    }
    public static final class id {
        public static final int action_settings=0x7f080000;
    }
    public static final class layout {
        public static final int activity_main=0x7f030000;
    }
    public static final class menu {
        public static final int main=0x7f070000;
    }
    public static final class string {
        public static final int action_settings=0x7f050001;
        public static final int app_name=0x7f050000;
        public static final int hello_world=0x7f050002;
    }
    public static final class style {
        /**
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.

            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.

        Base application theme for API 11+. This theme completely replaces
        AppBaseTheme from res/values/styles.xml on API 11+ devices.

API 11 theme customizations can go here.

        Base application theme for API 14+. This theme completely replaces
        AppBaseTheme from BOTH res/values/styles.xml and
        res/values-v11/styles.xml on API 14+ devices.

API 14 theme customizations can go here.
         */
        public static final int AppBaseTheme=0x7f060000;
        /**  Application theme.
All customizations that are NOT specific to a particular API-level can go here.
         */
        public static final int AppTheme=0x7f060001;
    }
}

R.java is an auto generated file which contains ids for the different resources (layout, drawable, string etc.) we have in our application. It provides access to all those resources through our code. From the code you can see that it contains static classes for different resources which contains the specific element. As this file is generated automatically, we should not make any changes to it.

Now lets take a look at the Android java code. Open the MainActivity.java file which is present inside the src folder and it will have the code as shown below

package com.example.helloworldapp;

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

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

At the top, there are three import statements. Our MainActivity class extends the Activity class which is present in the android.app.Activity class which we have imported. All our activity will need to extend the Activity super class.

Inside the class we have an OnCreate() method which is responsible for creating the UI of the activity. A savedInstanceState Bundle object is also passed to the method which contains the settings of the UI elements in the activity. Inside the function, we call the onCreate() method of the super class using the super keyword. After that the setContentView(R.layout.activity_main) sets the layout of the activity. You can note that we are passing our layout through the R keyword. This loads the layout of our XML file.

The other method onCreateOptionsMenu() created the options menu for that activity.

App Manifest File

Every Android application that you create will have an app manifest file called AndroidManifest.xml file. It contains the information about the application like the package name, application name, version etc. All the permission your app requires is also contained within the manifest. All the activity, content providers etc. are also defined in the file. You can see the contents below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.helloworldapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.helloworldapp.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

As you can see it lists the activity in the application. The <intent-filter> in the file specifies that the activity is the main activity and it should be started when the application is launched. It also specifies the minimum SDK version that is required by the application.

Configuring Emulator

Now its time to test out application in the Emulator. The Emulator mimics the functionality of a smart phone or a tablet. In Eclipse, go to Window –> Android Virtual Device Manager. This will open the Android Virtual Device Manager dialog which lists down all the emulators that you have created. As currently we don’t have any emulators, it displays “No AVD available”.

To create a new Emulator, click the “Create” button to open the Create Emulator Dialog. In the AVD name, provide a name for the emulator. In the Device field, select Nexus S and other options as shown below

You can also configure various options like memory, skin, front camera, RAM etc. After the information has been filled, click on Create button and the emulator will be created and listed in the AVD manager page. You can select the emulator and click on “Start” to run it.

To run our app in the emulator, right click the HelloWorldApp –> Run As –> Android Application.

The emulator will start and the app will be launched.

Though you can test you app in the emulator, it is always a good idea to test your app in an actual device before publishing it.

Debugging in Actual Device

To run and debug your application in a real device, you will need to enable USB debugging in the device. In previous version of Android, you can find the options Under Settings –> Applications –> Development. On Android 4.0 and newer versions, it is available under Settings –> Developer Options

The Developer Options is hidden in Android 4.2 and newer versions. Go To Settings –> About Phone and tap the Build Number 7 times to make it visible.

Once in Developer Options, Check the Android debugging option as shown below

You will also need to install the Google USB Drivers. Open the SDK manager and select the Google USB driver and install it.

Once the driver is installed, connect your phone to your computer with USB cable.

Open device manager and check whether it is getting displayed. Select your phone and click on “Update Driver Software” option

In the dialog that opens, select “Browse My Computer for driver software” and when it asks for file path, enter the file path as “F:\android-sdk\extras\google\usb_driver” . It may change depending on where you have installed the android sdk. The system will ask you whether you want to update the driver.

Click on install. Once it is done, you will see the listing under Android phone in Device Manager.

Now we are ready to run our app in our Android Phone. Right Click the HelloWorldApp project and click Run As –> Android Application. Now the system will present you with option of choosing between phone and emulator as shown below

Choose your connected phone and click Ok. The application will then be installed on your phone and executed. This is great for testing as well as debugging the app in a real phone. You can check the apps within to your phone and you will notice that “Hello World App” is visible there as well. The icon is the one which we have chosen while creating the project.

Creating APK File

Now that our application is tested on Emulator as well as device, it’s time to release it. To publish our app to the Playstore, we will need to create an apk file. In Eclipse, right click on HelloWorldApp project –> Android Tools –> Export Signed Application Package as shown below.

The Export Android Application dialog opens as shown below. Verify that “HelloWorldApp” is selected and click next

The KeyStore Selection dialog comes. Since we don’t have any existing key, select the “Create new Keystore” option. Provide the location of the keystore and provide the password. You will need to remember this password if you want to sign other apps using this key. Click on Next

The Key Creation Dialog opens. Fill the form by providing the info as shown below and click on Next

Then you will need to provide the destination where the apk file should be saved. Once done, click on Finish and the apk file will be generated in the path you selected

You can upload the apk file to the device or even upload it to Playstore. For actually uploading it to the Playstore, we need to provide the correct package name and other things but the process is the same.

One thought on “Getting Started With Android Development

Comments are closed.