Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

Hello Android - The Hello World Application

4.88/5 (64 votes)
19 Feb 2015CPOL33 min read 291.3K   5.1K  
learn to develop your first Android application

Index

Introduction

This article will guide you to create your first Android application. This application called "Hello World", it is a simple program that programmers write when they learn a new programming language or platform.

Background

"Hello World" application will only display the text "Hello World" on the screen but it is an importance step to make sure that your development environment is work properly.

The tools

In this article I will use an Android Studio to create the "HelloWorld" application, so you can download an Android Studio from it Official Download Page.

Note: Android Studio requires Java SE Development Kit (JDK) version 6 or higher. I recommend you to use Oracle JDK but if you want to use OpenJDK, you have to install OpenJDK version 7 or above.

Image 1

Create the Project

First of all, open an Android Studio and then click the File menu and select New Project...

If this is first time that you have run the program, you will see a project list window then click New Project... button at the right.

Image 2

This is the first screen that you will see after click "New Project..." button, it's used for setting up the project properties.

  • Application Name: The name of your application. In this example is HelloWorld.
  • Company Domain: Enter your company demain main name if you have. e.g. vable.me, google.com, etc. but don't worry if you don't have it, you can enter anything such as example.com.
  • Package Name: The name of Java Package, it is used to organize Java classes into namespaces. Java Package will naming by use your reversed domain name and follow by the application name. e.g. I use "android.vable.me" as domain name the Java Package will be "me.vable.android.helloworld". This step Android Studio will generate automatically.
  • Project Location: The location on disk that you want to store the project.

Then click "Next" button.

Image 3

This page is used to set a minimun version of Android that you want to support, I selected "API 9: Android 2.3 (Gingerbread)" because 99.1% of Android device running Android version 2.3 and above. I recommend you to consider the Android's feature that you want to use, the target user or percentage of Android user that will can use your app. The picture below shows the percentage of each version of Android.

Image 4

After you selected the Minimum SDK, click the "Next" button.

Image 5

This page is the list of Predefined Templates that you can use with your app. Select "Add No Activity" because we want to learn all basic of Android application development. And then click the "Finish" button.

Image 6

After that, you will see your workspace. Expand the "HelloWord" project in the Project Panel (on the left sidebar click "1: Project" if it not visible).

You will see the project structure, I will describe below.

Image 7

  • .idea folder: This folder contains the files that used by Android Studio. Don't touch it.
  • app folder: This folder contains a lot of files and folders, all of your code and resources is here.
    • build folder: It contains the files that build from you code.
    • libs folder: If you want to use external .jar library place it here.
    • src folder:
      • androidTest folder: The unit test code of your application.
      • main folder: It is a main work path
        • java folder: It contains your application code.
        • res folder: It contains your application resources.
        • AndroidManifest.xml: Config you Android application here.
    • .gitignore: git ignore configuration file If you use git for source control.
    • app.iml: Definition of your project structure.
    • build.gradle: Config about your project and dependencies here.
    • proguard-rules.pro: Need to protect your code? config here.
  • gradle folder: gradle build system folder.
  • .gitignore: git ignore configuration If you use git for source control.
  • build.gradle: Config about your work space here.
  • gradle.properties: Gradle config file.
  • gradlew: Executable file used for build the project (UNIX based).
  • gradlew.bat: Executable file used for build the project (Windows).
  • HelloWorld.iml: Definition of your project structure.
  • local.properties: Config your work space property.
  • settings.gradle: Config gradle that what project that you want to build.

I bolded the file or folder that you need to edit or need to know how it work.

Let's code

Create the MainActivity

First, we will create the Java class that inherit from "android.app.Activity".

Activity class in Android Application represents the single screen of an Android application, if you want to display something on the Screen, you need to create an Activity.

Expand the "java" folder and you will see your application package folder

Image 8

Right click on you package folder, select the "New" menu. You will see a lot of options, and yes it has an Activity option but now you should to create it by yourself without using template. Just click "Java Class".

Image 9

Image 10

This is a "Create New Class" screen, enter the Name as "MainActivity" and the Kind as "Class" then click "OK" button.

Note: Use the Pascal Case like Java class naming convention for Activity class and follow by the word "Activity" at the end.

You will get the code like this.

Java
package me.vable.android.helloworld;

public class MainActivity {
}


Add the import declaration to import Activity base class.

Note: Java use import declarations to make possible to call the classes in another packages with their simple name e.g. you can use "Activity" instread "android.app.Activity" if you have imported it.

Java
import android.app.Activity;

And then put the "extends" keyword to make MainActivity inherit from Activity class.

Java
public class MainActivity extends Activity {
}

Next, override the onCreate method for using to construct the UI.

onCreate method is a part on Android application life cycle that is used to create a UI to show on the screen.

TIP: You can type onCreate and then press Ctrl + Space Bar (on Windows OS) the suggestion will show.

Image 11

TIP: You can press Alt + Insert (on Windows OS) or right click in the code block that you want to see the list of something what you can generate.

Image 12

You will get the code like this.

Java
package me.vable.android.helloworld;

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

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}

Note: When you override a concrete method, don't forget to call the same method method of the super class by call super.<method name>(<methid parameter>);

What is the Bundle? android.os.Bundle is a class that is used to store and passing data between Activity or across application state.

Now, your Activity class is done but you can't use it until you tell the Android that your Application has a MainActivity class.

Add the Activity to AndroidManifest

AndroidManifest.xml is the file that store you application essential information, it is used to tell the Android that what is your application package name, the components of your app, the permission that this app request, etc.

From the Official Android Document

Quote:

Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest file presents essential information about your app to the Android system, information the system must have before it can run any of the app's code. Among other things, the manifest 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 <a href="http://developer.android.com/reference/android/content/Intent.html">Intent</a> 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 lists the <a href="http://developer.android.com/reference/android/app/Instrumentation.html">Instrumentation</a> classes that provide profiling and other information as the application is running. These declarations are present in the manifest only while the application is being developed and tested; they're removed before the application is published.
  • It declares the minimum level of the Android API that the application requires.
  • It lists the libraries that the application must be linked against.

Now, you have AndroidManifest.xml look like this

XML
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="me.vable.android.helloworld">

    <application android:allowBackup="true"
        android:label="@string/app_name"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/AppTheme">

    </application>

</manifest>

Let's see what is the meaning of each tag in this manifest file.

  • manifest element: The root element of manifest it decliar a namespace that will use in this xml file. It must contains an <application> element, xmlns:android, and package attributes.
    • xmlns attribute: Used to declare the namespace that you will use.
    • package attribute: You application package name, Android will use it to identify your application.
  • application element: It describe about your app such as application name, icon, and theme. This element will contains components of your app such as Activity, Service, and Provider.
  • activity element: It repersent your Activity class and its configurations.

Add MainActivity into the manifest by put <activity> element into the <application> element and enter the name as ".MainActivity".

Note: You must add <activity> element as the child of <application>.

Note: The android:name attribute is refers to the class path, you can enter a relative path from the main package or absolute path e.g. your class path is me.vable.android.helloworld.MainActivity and the package of manifest is me.vable.android.helloworld, you can use just .MainActivity or its absolute path.

XML
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="me.vable.android.helloworld">

    <application android:allowBackup="true"
        android:label="@string/app_name"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity" >

        </activity>

    </application>

</manifest>

OK, now you have tell the Android that you have the MainActivity class but the Android still don't know how it can run your application. You need to tell it what is the first activity that will be launch after application start.

<intent-filter> is used for describes that what the event that your Activity, Service, or Receiver will interacts. When the android calls the application to start activity or emit the event, it will find the responsible man of that event by look at the intent-filter list.

XML
<activity android:name=".MainActivity" >
    <intent-filter>
    </intent-filter>
</activity>

Next, you have to specific what the event that your Activity will interacts. The intent-filter can contains action, category, and data

  • <action>: It refers to the standard actions that indicate the interaction of components such as main, web search, pick, etc.
  • <category>: It refers to the kind of this component such as luancher, browser, etc.
  • <data>: The URI that references the data to be act. e.g. the uri of website to view.

When Android invokes the application to launch it will send the intent with the action android.intent.action.MAIN and the category android.intent.category.LAUNCHER. Write it to your manifest!!

XML
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="me.vable.android.helloworld">
    <application android:allowBackup="true"
        android:label="@string/app_name"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Note: It's not necessary to add intent-filter to every activity.

Build(Compile) an Application Project

Everytime after you code or edit something of your project, you need to build a project to Andtoid Application Package (APK) before deploy to Device or Virtual Device.

To build your project, click the menu "Build" on the toolbar then select "Make Project" (or you can use Ctrl + F9 as shotcut on windows OS)

Image 13

After made, Android studio will show the make result on the status bar (bottom of a screen) and you can yee a build message from the "0: Message" tab (above of the status bar) .

Image 14

When BUILD SUCCESSFUL the APK file will available in the path <project path>/app/build/outputs/apk you can deploy it to the device or emulator.

If build failed, it will tell you a reason of errors you need to fix it and build again.

Image 15

The picture above shows the error message of missing semi-colon(; ) try to fix it and build again.

Wow!! you application is almost complete but we need to test it on the emulator or real device.

Create the Virtual Device

The Android SDK provided an Android Virtaul Device (Emulator) for testing application without using real device, so you need to create Android Virtaul Device by click "AVD Manager" icon on the toolbar

Image 16

And then the Android Virtaul Device Manager window will appear.

Image 17

Click "Create..." to create Android Virtual Device.

Image 18

On the "Create new AVD" window there are many options that you can select, I will describe below:

  • AVD Name: The name of AVD, you can set as anything that you want but it must contains only charaters and number
  • Device: Select the device that you want to emulate. if the device that you want not exist, you can make you own custom device definition.
  • Target: The Android version of this AVD. select the version that support by your application. Sometime you need to test your application in many Andoird version, you can create emulators as many as you want.
  • CPU/ABI: You can spefic CPU of an Emulator. There are Intel, ARM, MISP, etc. in options you can select as you want. Intel cpu is run faster but sometime your application doesn't support Intel device. And you need to know that most of Android device powered by ARM.
  • Keyboard: Check it if you want to show hardware keyboard on the emulator window.
  • Skin: Set the emulator skin (UI).
  • Front Camera: Do you want to emulate Front Camera or use your PC camera or not?
  • Back Camera: Do you want to emulate Back Camera or use your PC camera or not?
  • Menory Options:
    • RAM: You can spefic ram of AVD but if you set it too large emulator may fail when start.
    • VM Heap: Set the AVD VM Heap size.
  • Internal Storage: the internal stirage of an emulator.
  • SD card: If you prefer to emulate write or read external storage, set the SD card size or select the file.
  • Emulation Options:
    • Snapshot: Check it if you want to keep the emulator state when turn off.
    • Use Host GPU: Use the PC GPU for emulation.

For the start you can set the options same as mine and then click "OK", the options summary page will appear.

Image 19

Create new Virtual Device Definition

Need a custom Virtual Device? Create it!!

From AVD Manager Screen click the "Device Definition" tab.

Image 20

Then click "Create Device..."Image 21

Here is a list of Device Definition Properties

  • Name: Device definition name.
  • Screen Size: The size of device screen in inch.
  • Resolution: Screen resolution in pixel.
  • Sensor:
    • Accelerometer: Check it if you want to use Accelerometer.
    • Gyroscope: Check it if you want to use Gyroscope.
    • GPS: Check it if you want to use GPS.
    • Proximity Sensor: Check it if you want to use Proximity Sensor.
  • Camera:
    • Front: Check it if you want to use Front Camera.
    • Rear: Check it if you want to use Back Camera
  • Input:
    • Keyboard: Check it if you want to use Hardware keyboard and select it type.
  • RAM: Total ram of AVD
  • Size: The size of device, it will set automatically when screen size was set
  • Screen ratio: Ratio of the screen. Most of devices screen is long but some device with hardware keyboard has a square screen.
  • Button: Check it if you want to use Hardware Button (Back, Home, App Stack).
  • Device State:
    • Portrait: Check it if you want to support display in Portrait mode.
    • Landscape: Check it if you want to support display in Landscape mode.

After config completed, click "Create Device" you will see your device definition in the list and you can create AVD from this definition

Image 22

Deploy your application to Virtual Device

Please make sure that your project was built.

Now, we will install the "HelloWorld" application to the Emulator. The easilest way is click the "Run 'app'" (Green Triangle) on the toolbar (or shortcut Shift + F10 on Windows OS).

Image 23


Then the "Choose Device" window will show.

Image 24

If you have running Virtual Devices or Real Devices it will show in the table select the device that you want to deploy an application, if nothing in table select Launch emulator and Android virtual device from the dropdownlist. If you want to use this device for future launches check the "Use same device for future launches" checkbox. Then click "OK" button the emulator will appear (if using emulator) and application will deploy.

Image 25 Image 26

Now, you see the emulator showing an application with blank content and application name on the top bar (ActionBar).

Can't run the App? read this

Preparing a Device for Development

If you have the Real Android Device you can deploy an application to your device directly but you need to set something.

Enable Developer options

On the real device, go to Settings then scroll down to the end. You will see the "About Phone" menu, tap it.

Image 27

You will see the "About Phone" screen scroll down to the end and tap on the "Build Number" for 7 times.

Image 28

After that Android will tell that "You are Developer", go back to settings you will see "Developer Options" menu.

Image 29

Tap it, you will see the "Developer Options" screen then turn it on and check "USB Debugging" as the picture below

Image 30

Now, your device is allow you to deploy an application for debugging.

Install ADB USB Driver (Required for Windows, Ignore if you use *nix)

When you connect the Android Device with Windows PC, Windows will not recognizes your device. You need to install a driver before use it, below is instruction to install the driver.

Open the Android SDK Manager from the menu "SDK Manager" on the toolbox of Android Studio

Image 31

Then the SDK Manager window will show. Scroll down you will see the "Google USB Driver" checkbox with status as "Not installed" check it (if there is your Device Manufacturer USB Driver checkbox such as Nokia, Samsung check it)

Image 32

Then click "Install <number> packages..." button.

Image 33

Read the License of each packages and accept it, then click the "Install" button.

Image 34

Image 35

Now, USB Driver was downloaded. You need to connect your Device with PC for installing driver. On the PC go to Device Manager (For windows 8.1 you can open Device Manager by right click on start button. For Windows 7 you can open Device Manager by right click on Computer and click Properties you will see the Device Manager link on the side menu)

Image 36

On Device Manager window find the Other devices you will see something with warning sign. In the picture the unknow device labeled as "Android Phone" (Sometime it show as the name of device) right click on it and select "Update Driver Software"

Image 37

Then click the "Browse my computer for driver software" option.

Image 38

Browse to the <Android SDK PATH>\extras\google\usb_driver then click "Next" button.

Image 39

When driver installed it will display as picture below.

Image 40

If after installed, the warning sign still appear or installation failed, please see the instruction from the Manufacturer website or manual.

Deploy your application to Device

To deploy the application to Android Device the method is as same as deploy an application to Emulator but when "Choose Device" window shown, select your device instread Emulator.

Click the "Run 'app'" (Green Triangle) on the toolbar (or shortcut Shift + F10 on Windows OS).

Image 41


Then the "Choose Device" window will show.

Image 42

If you connected to Android Device, it will show in the table, if nothing show, connect your device to PC via USB cable and then you will see it. Select the device that you want to deploy an application If you want to use this device for future launches check "Use same device for future launches". Then click "OK" button, the application will deploy and execute.

Image 43 Image 44

Now, your device showing an application with blank content and application name on the top bar (ActionBar).

Can't run the App? read this

Adding the View

Now, you can run an application on emulator and real device but nothig show on the screen because you haven't created it yet. In this section we will leard about using a simple View, and other resources.

App Resources

In Android Application Development you should exclude resources such as images, text, UI layout, etc. from the code. Android provided res directory for store resource files.

let's see the res directory. On the Project Panel expand the path <application name>/app/src/main/res you will see many subdirectories.

Image 45

  • res:
    • anim: The directory that is used to store animation config files.
    • drawable: The directory that is used to store graphic and graphic config files such as images.
    • layout: The directory that is used to store UI layout files such as screen layout, list item layout.
    • values: The directory that is used to store value content file suach as text, dimension, style, color.

Note: If you missing some res directory, you can create it yourself.

Note: You will see some directory has a qualifier such as drawable-xhdpi, values-v14 it is the mechanism to apply the different resources to specific device with that property. To see more about qualifiers go to Official Android Developer API Guides

Note: Most of file types in res directory is XML , Google design XML Schemas for specific works such as animation, UI layout, localization, etc. So you need to know some basic knowledge about XML.

R.java

All of your resources such as Layout, Animation, String, etc. can be accessed via Java code. When you add a Resources, the Android will re-generates R.java the file that defines your resource IDs that allows you to use the Resources fron Java code.

Image 46

The picture shows that you have the ic_launcher.png file in drawable<xxxx> folder and in the R.java you will have ic_launcher as the static int variable in drawable class too.

Example of accessing resource via java code

Java
getResources().getDrawable(R.drawable.ic_launcher);

You can access all Resources from the getResources() method and follow by the accessor method of each resource types with the resource ID as parameter.

The Layout

Layout Resource file is used to create the User Interface such as Screen, ListItem, Dialog, etc. it is simple a XML file but it's powerful.

Android doesn't use Pixel Coordinate to position the UI, because of there are lot of screen size, resolution, and aspect ratio that Android supported. Android provide a Layout to group View elements and align them. For the simple Layout, will describe below

  • LinearLayout: It is very simple layout, Every element in this layout will align as stack in horizontal or vertical orientation.
  • FrameLayout: It is the Frame that you can place you element in the top, center, bottom, or corner of it.
  • RelativeLayout: When you want to place the element with the position that depends on other element, the RelativeLayout is the answer.
  • GridLayout: If you want to align you element as grid, use GridlLayout it like the table that you can place the element into the cell, you can span the row and column.
  • AbsoluteLayout: The layout that allow you to place the UI element to the position with X,Y coordinate. Not recommended to use anymore, it is deprecated.

The Sizing

When Android not recommended to position UI by using cooridinate, it not recommended to fix the UI element size too. Android provided the specific unit and value for sizing the View.

  • MATCH_PARENT: Set the element size (width or height) to fit its parent.
  • FILL_PARENT: It same as MATCH_PARENT but it support Android version 2.2 and below.
  • WRAP_CONTENT: Set the element size (width or height) to fit its parent.
  • dp(dip) unit: It is an abstract unit that calculated from the physical density of the screen. Can use to define the size of element or it margin and padding.
  • sp unit: like the dp unit but it also calculate with user prefers font size, recomend to use for sizing text.

Let's Create the Layout (Screen)

To create the layout, you need to create the layout file in res/layout directory (create it if not exist).

Right click on the layout directory, select the New > Layout Resource file

Image 47

Enter file name as activity_main for indicate that this is an layout file for MainActivity.

Note: The naming convention of layout file is prefix with the class type such as activity, fragment, listitem, etc. and follw by the name such as main, detail, etc. and using only lower case letter, number, and underscore. e.g. You have an Activity name "MainActivity" the layout for this activity shoud be name as "activity_main.xml".

Image 48

You will see the window content look like this.

Image 49

This is an Layout Designer, it allow you to drag and drop UI elements on the screen and set them properties. The layout file is powered by XML file when you drag and drop or change something on the Design View, the XML code will change automagically. In the other hand if you code something on the XML View, it will affect to Design View.

Try to open the XML View by click the tab "Text" on the bottom of Layout Designer.

Image 50

You will see the XML code like this.

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

</LinearLayout>

Note: The root element of android Layout resource file must have the android namespace declaration.

Back to the Design View, try to drag the Large TextView from the Palette and drop on the device screen.

Image 51

Now, you have a TextView on the screen. If you want to add other elements, you can do it but in this article I will focus on the TextView.

Set the MainActivity to use activity_main.xml as it UI

Go to your MainActivity, find in the onCreate() method and put the setContentView() statement with your layout ID as it parameter.

Java
package me.vable.android.helloworld;

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

public class MainActivity extends Activity {

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

}

Now, You can run the application to test the result.

Try to edit the properties

Back to the activity_main.xml's XML View, you will see the code:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView" />
</LinearLayout>

There is a <TextView> element appered as the child of LinearLayout.

Note: You can set the properties from the XML code or using the GUI Properties Panel on the left bottom of Design View.

Try to change TextView properties to:

XML
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Hello Android"
    android:id="@+id/textview_hello_android" />

Back to the Design View, you will see the text "Hello Android" on the screen.

Image 52

Here's the some View Properties explaination:

  • android:id - The ID that is used to refer this View. Android will generates the ID resources from this attribute.
  • android:layout_width - Width of the View, you can see the possible values from The Sizing Topic
  • android:layout_height - Height of the View, you can see the possible values from The Sizing Topic
  • android:text - The text that you want to show, can set as hard code string or string resource
  • android:textAppearance - The appearance of text
  • android:layout_margin - The gap between this View and other View. The possible value is the hard code of dimension type such as 8dp or the dimension resource.
  • android:padding - The gap or area around the View (inside) that not allow to place the content. The possible value is the hard code of dimension type such as 8dp or the dimension resource.
  • android:gravity - The property that define about where to place the content in this View such as on the left, right, center, etc.
  • android:layout_gravity - The property that define about where to place this View on it Parent View such as on the left, right, center, etc.

Image 53

Image 54

The picture shows the margin, padding, and content area. The margin is the picture represent by the orange color, it is the View outside area that act as the gap between Views. The yellow one is padding, the area that not allow to place any content. On the center, it is the content display area if the content area is larger than it content, you will see that the content is alway place on the top left except you have set the android:gravity property.

Now, The Hello Android application is completed. But we will learn more about some simple Resources.

The String Resources

The Resource Type that provides static text strings, plural string, and string array. Android recommend you to use the string resources instread the hard code string.

Benefits of String Resources

  • Place strings in one place - It's meant more managable, you can edit the string without waste time for finding where it place.
  • Device Oriented - You can display different string for different screen size by using the resource qualifiers.
  • Internationalization and Localization - When Android allow you to serve different resource for different device with qualifiers-suffix, it allow you to create the multilingual application too. You can create the String Resources in the folder values-<language code> for specific language e.g. if you have String Resources in folder values-th when your application running on the device with Thai as display language the Android will use the string from values-th instread values.
  • Reusable - Yes, you can reuse the string as you want. If you have many element that display same string, you can use only one string resource.

Try to use

The String Resources is place in the res/value(-xxx)

Image 55

By deafult when you create the project, string.xml will create automatically. Open string.xml you will see the XML code like this.

XML
<resources>
    <string name="app_name">HelloWorld</string>
</resources>

There is only the string resource name "app_name" that is used to set you application name in Manifest file. I recommend you to create a new string resources file by right click on the values folder and select the "New > Values Resource files" option.

Image 56

Name it as activity_main_strings.xml for indicate that this strings file use for display on MainActivity, then open it.

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

Create the string for Hello Android TextView.

XML
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="textview_hello_android">Hello Android!!</string>
</resources>

Now, open you MainActivity layout file and try to use the string resources instread the hard code string.

Note: In XML code you can refer to you string resource by using @string/<your string resource name>.

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/textview_hello_android"
        android:id="@+id/textview_hello_android" />

</LinearLayout>

Image 57

You will see the result in the preview screen or the Design View. To make sure that your project is work properly, run the application on your device or emulator.

Image 58

Internationalization & Localization

You can localize your application by translate your string resource and place it in to a directory name "values-<language code>". For the support language list you can find that from this Stack Overflow Thread

I will create Thai string resources for an example.

First, create a directory in res/ name values-th

Image 59

Second, create the string resources file or copy it from the values directory.

Image 60

Now, open it and put the translation text.

Note: Must use the same string name with string resources in values directory.

XML
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="textview_hello_android">
        สวัสดี แอนดรอยด์!!
    </string>
</resources>

Image 61

Finally, Test on the device or emulator that use Thai as display language.

For set the display language, got to the Settings > Languages & Input > Language then select the language that you want.

Image 62

This is the result. The text "Hello Android!!" has been translated to "สวัสดี แอนดรอยด์!!"

Note: The string that has no translation will display as it original string (from values directory).

Note: When you sign an Application for distribution the error will throws if some string have no translation. You need to translate all strings to the language that you want to support.

Image 63

To translate an application name, just copy values/strings.xml to values-th/strings.xml and translate it.

XML
<resources>
    <string name="app_name">สวัสดีชาวโลก</string>
</resources>

Image 64

Image 65 Image 66

The application name under the icon will change too. (if it not change, you can uninstall the application and install again)

The Color Value Resources

In XML you can use hard code Color Value for color the View component. Like the string value, you can create it as resources too.

Now, let's create color.xml in the values directory

Image 67

Open it you will found the code that look like other value resource

Note: All of value resources can be put in one file because it has same structure but I recommend you to create a file separately for easy to manage inthe future

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

Add a color resource by put the color tag with name attribute and it value as color code

XML
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="orange">#FF7411</color>
</resources>

I create a color name orange with the color code #FF7411.

Let's try to use it to set text color in activity_main.xml.

XML
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/textview_hello_android"
        android:id="@+id/textview_hello_android"
        android:textColor="@color/orange"/>

Image 68

Now, your TextView's text is orange.

Note: android:textColor is used to set the color of text.

The Dimension Resources

To sizie and position the View you can use a static value in dp, sp, px units, we will make it as a resource too.

When you make dimension value as resources, you can edit a value in one place and affect to all View that use this resource.

Now, let's create dimens.xml in the values directory

Image 69

And then put some dimens resource in to it.

XML
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="margin_default">16dp</dimen>
</resources>

I have created a dimens value for using as a default margin of View.

Try to use it to set margin of TextView in activity_main.xml.

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/textview_hello_android"
android:id="@+id/textview_hello_android"
android:textColor="@color/orange"
android:layout_margin="@dimen/margin_default"
/>

Now, the margin applied.

Image 70

Note: android:layout_margin is used to set the the gap between current View and other Views.

You can also try to use with another properties such as padding, width, height, etc.

Sign the application for Distribution

In the APK packaging process your application contents will sign with the private key. You will can't install your application if it not signed.

For debugging or testing application, Android Build Tools will check for a debug keystore if it not exist Android SDK will generate a new one and use it to sign the debug APK.

KeyStore is a repository of security certificates, Android use it to store certificates (keys). The keystore file is unique that meant it impossible to create a same keystore if it lost and you will can't update your application.

When you deploy the Debug APK to device from one PC and then you re-deploy the application from another PC, Android tell you to uninstall an old one before install again becuase it think that 2 Debug APKs are come from different owner and they are different application.

When you want to distribute your appliacation you need to sign you application with your own private key not a debug key.

Create your own keystore

With the Android Studio, you can create your own certificate in a GUI tool. Click the Build menu and select the "Generate Signed APK..." option the Wizard will appear.

Image 71

Click the "Create new..." button to create a new one.

Image 72

Browse the location what you want to store the KeyStore and enter a name.

Image 73

Then enter the other information:

  • Key store path: The path of the KeyStore file you just select in previous step.
  • Password/Confirm: Password of the KeyStore (Remember it).
  • Key: It is the certificate, in contains of private key and public key..
    • Alias: Alias of the certificate (Remember it).
    • Password/Confirm: Password of this certificate (Remember it).
    • Validity (years): The amount of year that this certificate valid.
    • Certificate:
      • First and Lasrt Name: Your full name.
      • Organization Unit: You organization unit.
      • Oraganization: Your organization name.
      • City or Locality: Your organization city.
      • Statr or Province: Your organization province.
      • Country Code: Your organization country code.

Image 74

Then click the "OK" button. The keystore will create or the error will throws.

Image 75

You will see that the wizard will fill your keystore and alias automatically and there is an option to remember a password, however you need to remember the keystore information by yourself.

Then, click the "Next" button.

Image 76

You can select an Signed APK destination folder (if it not exist, create it by yourself), and the Build type (by default there are release and debug options. Select "release" if your want to distribute). Then click the "Finish" button.

Image 77

The APK signing result will show on the status bar and its build message will show on the "0: Message" tab.

If it tell something error or missing, you need to fix it and sign again.

After signed, you can distribute your application to other, and upload to the Store.

Note: KeyStore file can contains one more more alias but I recommend you to create only one alias for one KeyStore.

Note: The alias is an actual certificate. You need to use only one alias to sign the application, if you sign the application with different alias you will can't update your application.

Can't run the App? read this

Richard MacCutchan ask me that he can't run the application and got the error message:

08-11 14:27:15.990      863-863/me.vable.android.helloworld D/dalvikvm﹕ Not late-enabling CheckJNI (already on)
08-11 14:27:16.600      863-863/me.vable.android.helloworld D/AndroidRuntime﹕ Shutting down VM
08-11 14:27:16.600      863-863/me.vable.android.helloworld W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb2ac8d70)
08-11 14:27:16.610      863-863/me.vable.android.helloworld E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: me.vable.android.helloworld, PID: 863
    java.lang.RuntimeException: Unable to start activity ComponentInfo{me.vable.android.helloworld/me.vable.android.helloworld.MainActivity}: android.util.AndroidRuntimeException: You cannot combine swipe dismissal and the action bar.
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2197)

This error message is interesting because it is not a programer fault but it is an Android compatibility issue, when you try to build the app with target to the Android 4.4W or Android L you will can't install or run it on the older version Android devices.

Let's see the app.gradle file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 20
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "me.vable.android.helloworld"
        minSdkVersion 9
        targetSdkVersion 20
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}
  • apply plugin: 'com.android.application' - This statement is used to import Android Build plugin.
  • android - Android Configuration
    • compileSdkVersion - The version of Android SDK that you use to build the app. Should be the same as targetSdkVersion.
    • buildToolsVersion - The build tool version.
    • defaultConfig - Default Configuration for Application build.
      • applicationId "me.vable.android.helloworld" - Package name of your application.
      • minSdkVersion - The lowest version of Android that you want to support.
      • targetSdkVersion - The target version of Android for this application. Enter the version of your device or highest as possible.
      • versionCode - Version of the code.
      • versionName - Version name of the code.
    • buildTypes - Declairation of Build Types
      • release - Name of Build Type
        • runProguard - Want to use proguard?
        • proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - Proguard rule path.
  • dependencies - Config the libraries here.
    • compile fileTree(dir: 'libs', include: ['*.jar']) - import all .jar libraries in the libs folder.

The cuase of error that Richard MacCutchan found is the compileSdkVersion and  targetSdkVersion that he set to version 20. I ask him to set the compileSdkVersion and  targetSdkVersion to 19 or below and test again. And he tell me it work properly.

The conclusion, you should to set the targetSdk and compileSdk to 19 or below to fix this problem untill Google fix Android 4.4W and Android L compatibility issue.

Note: When you want to upload the Update for your application to the Store you need to increase the versionCode and versionName. e.g. old versionCode is 1 and versionName is "1.0.0.0" you need to set versionCode to 2 or heigher and set the versionName to something that not same as old version such as "1.0.0.1" or "2.0.0.0"

apply plugin: 'com.android.application'

android {
    compileSdkVersion 19
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "me.vable.android.helloworld"
        minSdkVersion 9
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

**After the Android Lollipop was released there are no compatibility issues but you need to update android support library to v 21+

If you got other problems, you can ask me by reply this thread

Point of Interest

Congratulations, you have created your first Android Application. Your have learned about the Basic of Android Application Development, this is the most importance step to understand what you will learn in the future. I hope you enjoy your Android Application Developer Life,

History

  • 01/08/2014 First release.
  • 01/08/2014 Add completed project download link.
  • 01/08/2014 Fix the style to CodeProject Standard and try to correct sentences.
  • 01/08/2014 Fix the layout and try to correct sentences.
  • 01/08/2014 Fix article index link.
  • 01/08/2014 Remove all custom CSS becuase of the CodeProject article writing rule.
  • 02/08/2014 Correct some sentence errors.
  • 05/08/2014 Correct misspelled words.
  • 06/08/2014 Correct misspelled words.
  • 13/08/2014 Add a problem and explaination.
  • 13/08/2014 move download link to the top.
  • 16/08/2014 Correct misspelled words.
  • 19/08/2014 Add more picture.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)