Java Techies- Solution for All
Android Hello_World Example
Welcome to actual Android application development! This class teaches you how to build your first Android application. You will learn how to create an Android project and run a debuggable version of the application. You will also learn some fundamentals of Android app design. Before you start this session, be sure you have your development environment set up properly, as we discussed earlier in Android Environment Setup.
Let's start writing a simple Android Application which will print "Hello World!".
Create Android Application
First step to create a simple Android application using Eclipse IDE, File -> New -> Project and finally select Android Application Project from the list. By selecting Android Application Project new window will appear to name your application, Name your application as given below-
Now, follow the instructions provided for the next steps and keep all other entries as default till the final step. After creating project successfull , you will have the following project screen.
Anatomy of Android Application
Before you run your first Android application, you should be aware of a few directories and files used in the Android project :
S. No. | Folder/File | Description |
---|---|---|
1. | src | This contains the .java source files for your project. By default, it includes an MainActivity.java source file having an activity class that runs when your app is launched using the app icon. |
2. | gen | This contains the .R file, a compiler-generated file that references all the resources found in your project. You should not modify this file. |
3. | bin | This folder contains the Android package files .apk built by the ADT during the build process and everything else needed to run an Android application. |
4. | res/drawable-hdpi | This is a directory for drawable objects that are designed for high-density screens. |
5. | res/layout | This is a directory for files that define your app's user interface. |
6. | res/values | This is a directory for other various XML files that contain a collection of resources, such as strings and colors definitions. |
7. | AndroidManifest.xml | This is the manifest file which describes the fundamental characteristics of the app and defines each of its components. |
There are also some important application files about which you have to know before run your application. Following given section will also give a brief overview about these important application files.
The Main Activity File
The main activity file is a Java file MainActivity.java, which is the actual application file which ultimately gets converted to a Dalvik executable and runs your application. Following is the default code generated by the application wizard for My_First_App application :
package com.jtechies.my_first_app; 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; } }
Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder. The onCreate() method is one of many methods that are called when an activity is loaded.
The Manifest File
Every Android application must have a manifest file called AndroidManifest.xml in its root directory. The manifest presents essential information about the application to the Android system, information the system must have before it can run any of the application's code.
All components develop as a part of an application, you must declare it in AndroidManifest.xml. Manifest file works as an interface between Android OS and your application. So it is necessary to declare all application components in this file, if you do not declare any component in the file, then it will not be considered by the OS.
Among other things, the manifest file does the following :
- It names the Java package for the application. The package name serves as a unique identifier for the application.
- It describes the components of the application - the activities, services, broadcast receivers, and content providers that the application is composed of. It names the classes that implement each of the components and publishes their capabilities (for example, which Intent messages they can handle). These declarations let the Android system know what the components are and under what conditions they can be launched.
- It determines which processes will host application components.
- It declares which permissions the application must have in order to access protected parts of the API and interact with other applications.
- It also declares the permissions that others are required to have in order to interact with the application's components.
- It declares the minimum level of the Android API that the application requires.
- It lists the libraries that the application must be linked against.
The default manifest file will look like as following :
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/android" package="com.jtechies.my_first_app" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name= "com.jtechies.my_first_app.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>
Here <application>...</application> tags enclosed the components related to the application. Attribute android:icon will point to the application icon available under res/drawable-hdpi. The application uses the image named ic_launcher.png located in the drawable folders.
The <activity> tag is used to specify an activity and android:name attribute specifies the fully qualified class name of the Activity subclass and the android:label attributes specifies a string to use as the label for the activity. You can specify a number of activities using <activity> tags.
The action for the intent filter is named android.intent.action.MAIN to indicate that this activity serves as the entry point for the application. The category for the intent-filter is named android.intent.category.LAUNCHER to indicate that the application can be launched from the device's launcher icon.
All the elements that can appear in the manifest file are listed below in alphabetical order. These are the only legal elements; you cannot add your own elements or attributes.
- <action>
- <activity>
- <activity-alias>
- <application>
- <category>
- <data>
- <grant-uri-permission>
- <instrumentation>
- <intent-filter>
- <manifest>
- <meta-data>
- <permission>
- <permission-group>
- <permission-tree>
- <provider>
- <receiver>
- <service>
- <supports-screens>
- <uses-configuration>
- <uses-feature>
- <uses-library>
- <uses-permission>
- <uses-sdk>
The String File
The strings.xml file is located in the res/values folder and it contains all the text that your application uses. For example, the names of buttons, labels, default text, and similar types of strings go into this file. This file is responsible for their textual content. The default strings file will look like as following :
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">My_First_App</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> </resources>
The R File
The R.java file is located in the gen (Generated Java Files) folder, it file is the glue between the activity Java files like MainActivity.java and the resources like strings.xml. It is an automatically generated file and you should not modify the content of the R.java file. Following is a sample of R.java file :
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.jtechies.my_first_app; 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; } }
The Layout File
The activity_main.xml is a layout file located in res/layout directory, that is referenced by your application when building its interface. You will modify this file very frequently to change the layout of your application. For your "My_First_App" application, this file will have following content related to default layout :
<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>
This is an example of simple RelativeLayout. The TextView is an Android control used to build the GUI and it have various attribuites like android:layout_width, android:layout_height etc which are being used to set its width and height. The @string refers to the strings.xml file located in the res/values folder. So, @string/hello_world refers to the hello string defined in the strings.xml file, which is "Hello World!".
Running the Application
To run the My_First_App application, we just created, you had to create your AVD while doing environment setup.Now open one of your project's activity file and click Run icon from the toolbar. Eclipse installs the application on your AVD and starts it. It will display following Emulator window :