ADT Android Bundle to Quickly Setup Android Development

Start Writing Google Apps on Windows

If you want to write Android Applications (Apps) you need the right software. Google provides free access to this software for Windows, Apple Mac and Linux PCs. An App is a computer program and like all programs it needs designing, writing, compiling, testing and debugging. This is all done in an Integrated Development Environment (IDE). There are many IDEs from which to choose. This article deals with the IDE provided by Google in the ADT Bundle for Windows. So read on for tips and information on installing and running the ADT Android bundle.

Use the ADT Android Bundle For Android Apps

Apps are written in computer language. Google’s preferred language for Android is the widely used Java. A popular IDE for writing Java programs is called Eclipse, from the Eclipse Foundation. The Eclipse IDE can be installed on to most PCs, including Windows PCs. For Android App development the Eclipse IDE requires the Android Software Development Kit (SDK) and the Android Development Tools (ADT), both from Google. All of these (Eclipse, SDK and ADT) are available in a large zip file from the Android Developers web site, the ADT Bundle for Windows.

Alternative Android App Development Environments

The ADT Android bundle is not the only option from Google. Instead of using the large zip file, install Eclipse, the Android SDK and ADT in separate steps. Good for those who need more control over the installation. (See our article Setup Android Development on Windows.)

A new option from Google is the Android Studio. Studio is currently under development so is only available under a beta release and thus subject to change. Studio does not use the Eclipse IDE, it uses the IntelliJ IDEA environment thus giving you a choice of editors. To set up Android Studio see our article Android Studio Install for Windows Based PCs.

Apps can be programmed in computer languages other than Java, using IDEs from companies other than Google. See the last section of this article for alternatives to using Java.

Install Java JDK

Java is Google’s preferred language for App development. As such the Java runtime and development kit needs installing before the ADT Android bundle. Go to the Java download page at http://www.oracle.com/technetwork/java/javase/downloads/index.html.

The Java Download Button

Select the Java download button and follow the instructions. Accept the license agreement and select the correct Windows installation EXE for your PC. (If unsure whether you are running 32-bit or 64-bit Windows use the System option in Control Panel. Under Basic Information the System type tells you if it is a 32-bit or 64-bit Operating System.) Run the Java installer to set up Java on your PC. See our article Installing Java on Windows (32-Bit or 64 Bit) if you need more help.

Download ADT Android Bundle

The Android SDK download page is at http://developer.android.com/sdk/index.html. Click on the Download the SDK ADT Bundle for Windows button. Accept the Terms and Conditions displayed by clicking the check box. Choose either 32-bit or 64-bit to match your Windows installation.

Another Download the SDK ADT Bundle for Windows button is enabled. Click the button to save the adt-bundle-windows-x86-YYYYMMDD.zip (32-bit) or adt-bundle-windows-x86_64-YYYYMMDD.zip (64-bit) file to your PC. Where YYYYMMDD is the release date for the package. E.g. adt-bundle-windows-x86-20130717.zip is the 32-bit ADT Android bundle released on July 17th 2013.

Extract Zip File Contents to Install Eclipse IDE and Android SDK and Tools

All the contents in the zip download need to be extracted. This can be done with Windows Explorer, however, on Windows XP you may get errors copying the files using Explorer. If so use an archive tool, such as 7Zip, to extract all the ADT Android bundle files.

The Android Developers website recommends extracting to a “Development” directory under your normal home location. However, that means a lot of program files are stored with your normal work. Some Android developers extract to C:\Program Files (this is a protected directory and you made be asked for permission to copy here), other developers install to a directory on the root of C: or other hard drive, such as C:\Android or C:\Development. Since the zip file contains a root directory named after itself simply copy that directory to a hard drive root. For example the contents of adt-bundle-windows-x86-20130717.zip can be extracted to C:\adt-bundle-windows-x86-20130717.

Add a Shortcut to Eclipse to the Desktop

Eclipse ShortcutTo access the App development environment quickly add a shortcut to your PC desktop. Using Windows Explorer open the eclipse directory in the extracted contents. Bring up the context menu (usually right-click) on the eclipse.exe program and select Create shortcut. Drag and drop (move) the new shortcut onto the desktop.

Run It!

The ADT Android Bundle is now installed. Run the eclipse.exe program (you can use the shortcut if you created one). First time in you will be asked to contribute usage statistics to Google. Select Yes or No and press the Finish button.

Create an Android Virtual Device (AVD) using the AVD Manager. An AVD allows testing of Apps without the need to use a physical device. Use the toolbar icon or select Android Virtual Device Manager from the Window menu. See our article Set Up an Android Virtual Device for App Testing for further information.

To test on a physical Android device install the manufacturers driver. With the driver installed use a USB cable to connect the device to your PC. You will need to enable USB debugging in the device settings.

Test your ADT Android Bundle installation by creating a simple App. See our article Your First Android Hello World Java Program. If you installed the ADT bundle to a drive other than C: you may get issues trying to run an App on an AVD. See our article Windows Symbolic Links for Android Installations on the D: Drive for a solution.

ADT Android Bundle Install Summary

Here is a summary of installing the ADT Bundle for Windows:

  • Download and install the Java JDK.
  • Download the ADT Bundle for Windows zip file.
  • Extract the contents to your PC.
  • Run it! (eclipse.exe).

Other Android App Development Options

If you struggle developing in Java, with the Google recommended IDEs for App development, there are other options. See our post Android Development Options, Tools and IDEs. It lists alternative development packages and languages.

AVD Sound Playback for Android App Testing

No AVD Sound When Testing an Android App?

On creating an Android Virtual Device (AVD) audio playback is normally OK. However, if using an old saved AVD there may be no AVD sound. When this happens messages may be seen in LogCat, including one or more of the following. (It varies by the API level of the AVD.):

AudioTrack Error obtaining an audio buffer, giving up.

AudioTrack obtainBuffer timed out (is the CPU pegged?).

AudioFlinger could not create track, status: -12.

Be aware that the last error is also seen with other sound playback issues. These other issues are usually memory related: such as the audio file is to big; too much data in the file (e.g. sample rate to high or varies to much); or the limit (32) on the number of audio tracks attempting to be played has been reached.

Note: If you don’t see messages in LogCat the following solutions may still apply. But also check that the PC’s sound is not off! (Or turned down low). Even forgetting to unplug headphone may be why you have no AVD sound.

Solutions to Try When You Can’t Play AVD Sound

In earlier editions of the Android Software Development Kit (SDK) the AVDs may not have been created with audio playback enabled. Subsequent SDKs enabled audio when an AVD was created. If an AVD is started and there is no AVD sound try the following:

  • Uncheck Launch from snapshot when starting the AVD.
  • Edit the AVD config.ini file to set Audio playback support to yes.
  • Delete the AVD and recreate it.
  • Use a physical Android device.

He is a bit more detail on each solution for no AVD sound. (Please ensure that the Android SDK is up to date as well). Continue reading

How to Get View Size in Android

Determining the Size of an Android View or Screen at Run Time

For efficient bitmap handling or dynamic View creation in an App the area that a widget or layout is using needs to be known. If no fixed sizes are allocated at design time the size of a View may not be known until an App is executed. This is because of the wide range of display sizes that Android supports. The example code snippets in this articles shows how to read the screen size and the size of Views as the App runs. To run the example code you will need to create a new Android project (those new to Android programming can view the article Your First Android Hello World Java Program to see how), we called our App View Size.

In the layout designer for activity_main.xml (or whatever you called your layout) add another TextView, called textXY, next to the existing Hello world! widget. Change the Text on the first TextView to X,Y. Add this code to the oncreate method in MainActivity.java (or whatever class you are using), you will need an imports for TextView and DisplayMetrics. :

This is the code running on an AVD with a 320×480 screen:
Size of Android Screen

He is the layout used for this screen: Continue reading

Access Android View in Activity

In Android Get View Defined in XML in Activity Code

The UI screens for an App can be designed outside of the code. They are stored in XML files. This eases support for multiple screen sizes and types and helps with software maintenance. Classes in the Android SDK have methods used to access the UI components. Screens are composed of various implementations of the Android View class. The major sub-classes for Views are widgets and ViewGroups. The widget class is not to be confused with Widgets that can be added to the Android home screen. Instead View widgets are the normal components with which the Android device users interact, including the ButtonCheckboxEditText (a text box), ImageViewRadioButtonProgressBarTextView (label) and many more. Several widgets sit in a ViewGroup which provides a container for laying out components. Different ViewGroups provide different types of layouts, including RelativeLayoutLinearLayoutScrollViewWebView and others. ViewGroups can contain other ViewGroups as well as widgets therefore building complex displays by nesting different Views is possible.

Create a Basic Android Screen

A Simple Android ScreenFor this tutorial create a new, simple Android App project and call it Button Demo (if you don’t know how see Your First Android Hello World Java Program). A simple screen that just has a button on it was created using the starting layout, we kept the default layout name of activity_main.xml. In Eclipse use the Package Explorer to open the activity_main.xml file (in the res/layout folder). Using the Graphical Layout view (selected via the tabs at the bottom of the editor window) delete the TextView, showing Hello world!, and drag and drop a Button from the Form Widgets folder onto the screen. This screen’s code is stored in the activity_main.xml file:

To show how this view is accessed from the App’s code the text on the button will be changed and it displays a message when it is clicked. Continue reading

Center a TextView on a Android Screen

Understand How Layouts Center Views

Android RectanglesSetting the correct XML attributes to move a ViewGroup or widget (View) to the middle of the App’s display is easier if you know how Android screens are laid out. Everything on the screen is built up in rectangles, starting with the screen itself. A LinearLayout (which is a ViewGroup) sitting on the screen is a rectangle, a TextView in the LinearLayout is a rectangle. Each rectangle has two sets of layout attributes associated with it, attributes that refer to its contents and attributes that refer to its parents layout requirements. The latter is easy to determine because they all start with layout_. The number of layout_ attributes that a widget, such as a TextView, can access will vary depending upon the ViewGroup it is inside:

ViewGroup LayoutParams List

To help remember that the layout_ attributes refer to the items parent ViewGroup think of it as “attributes that lay outside” of the rectangle.

The two layout_ attributes that are always required are android:layout_width and android:layout_height. These are set to tell the parent ViewGroup how big the rectangle should be to contain the child widget or ViewGroup. These are usually set to either match_parent (previously known as fill_parent) which lets the ViewGroup decide how big the rectangle should be (usually as big as possible), or wrap_content which makes the rectangles just big enough to hold what is inside of them. However, they can also be set to physical dimensions, such as setting layout_height to 40px to make the View’s height 40 pixels high.

Centring Android TextWhen a new Android project is started in Eclipse with a blank Activity some default Hello world! text is displayed in a TextView. What if we wanted to center this in the middle of the screen (note we use the American spelling instead of the UK spelling of centre to match the Android SDK API settings). Looking at the various layout attributes for the TextView it would appear that android:layout_gravity=”center” would work. This though has no effect because the default RelativeLayout arranges child Views based on each others position. Instead to center the TextView set android:gravity=”center” for the RelativeLayout. Because this attribute does not start with layout_ it refers to it contents, in this case the TextView. This time centering works, provided the TextView’s  android:layout_width and android:layout_height are set to wrap_content, making it small enough to be moved to the central location.

See also the Layouts article in the developer documentation.

How to Set a Color In Android

Changing Colors in Android and Naming Them for Convenience

An Android color is a 32-bit integer value consisting of four eight bit parts, ARGB. The four parts are the amount of red, green and blue that is in the color, plus how opaque (see through) is the color, which is called the alpha value, the lower the alpha value the more transparent the color appears. (Note that in the United Kingdom color is spelt colour.)

The alpha value is the highest (first) byte in the 32-bit value followed by the red, then green and finally the blue byte. Hence it is referred to as an ARGB value with each letter representing the type and order of the byte. This format allows for easy representation as a hexadecimal number in Java:

The three byes representing the color values provide over 16 million color possibilities in Android (256 x 256 x 256 = 16,777,216). A color depth better than the human eye (stated in the Wikipedia article). Plus all these colors can range from transparent, 0, to opaque, 255.

Named Color Resources in Android

To help with handling colors in Android they can be made into a resource for easy of reuse. Either open an existing resource file or create a new one. For example in Eclipse with a Android project open select the res/values folder. Then use the File menu (or the context menu on the values folder) to add an Android XML File. Give the file a name, e.g. colors.xml and add a color element:

Use getColor() to read the color value from the resource.

If the color is solid (full alpha value) then the color resource can leave the alpha value out. Though for clarity and future maintenance it is wise to be explicit and always define all four parts of an Android color: Continue reading

Starting Emulator Failed to Allocate Memory

What to Try When The Android Emulator Reports A Memory Allocation Error

Occasionally when starting an Android Virtual Device (AVD) or running a project that starts an AVD in Eclipse an allocate memory error is reported. In the Starting Android Emulator dialog a message is seen similar to this one:

Starting emulator for AVD ‘Name of AVD’
Failed to allocate memory: 8
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application’s support team for more information.

For example:

Android Failed To Allocate Memory

This article examines the reason for this error and possible solutions.

Why AVDs Need Large Amount of Memory

The latest Android devices now come with large memories, 1 GiB is now normal, and even larger memories will come in the future. When developing Apps for such devices it is natural to test them on AVDs that have the same specifications as the real world devices. When an AVD is set up using the AVD Manager program it is possible to choose existing device definitions. The Nexus 7 definition sets the RAM to 1024 MiB (1GiB). The RAM setting for the AVD is not all the RAM that the AVD uses. More RAM is required by the system to host and run the emulator code. An AVD given 1024 MiB can use up to 1.5 GiB when it is running. It makes having a high specification machine important when developing Android Apps.

Why AVD Memory Allocation Fails

The Failed to allocate memory:8 error usually occurs because the AVD is configured to have a large amount of RAM (>768 MiB) and the host Operating System (OS) appears not to be in a position to allocate that amount to the AVD (remember it needs to allocate more than specified because of the overhead in running the AVD). The OS may have plenty of memory available but it seems it is not currently in a position to allocate such a large chunk. For example the following screen shot shows the memory status on a Windows 7 64 bit machine with 8GB of memory that displayed the above error when an AVD to emulate a Nexus 7 attempted to start:

Windows resmon Example

This screenshot from the Windows Resource Monitor utility (perfmon.exe /res) shows virtually no free memory, but that is OK because there is plenty of Standby memory, 5.7 GiB. Standby is the memory cache and is available to newly starting programs (Windows will free cached memory when other programs need it). So why did the AVD fail to get a memory allocation? Continue reading

What are DPI, DIP, DP, PPI, SP and Screen Resolutions in Android?

Understanding Android Screen Densities and Terminology

Portrait v LandscapeThis article provides an overview of Android screen densities and the various acronyms that occur when dealing with a device’s screen. Android’s popularity as a mobile device Operating System has resulted in a proliferation of hardware on the market. This has provided great choice for the consumer and forced continuous innovation from the manufacturers. In a few short years there has been rapid innovation in all areas: CPU capabilities, memory size, form factors, keypads, cameras, sensors, batteries, power consumption and screen technologies. The screens have been getting bigger, thinner, sharper, tougher and more responsive to touch. This has forced the Android SDK to move rapidly with the hardware technology (and the hardware to feed upon Android ideas). Explained here is how the variety of screen sizes are handled by the OS, finishing with a summary table of the acronyms covered.

What makes up an Android Screen

Android Coordinate SystemFor those of you new to technology here’s how a device screen works. The screen is made of thousands of small dots called pixels arranged in a grid. The pixels running from left to right are known as the X pixels or X-axis. The pixels running from top to bottom are known as Y pixels or Y-axis. The resolution of the display is the number of pixels in X-axis multipled by the number of pixels in the Y-axis. A 320 by 480 display will have 320 pixels in the X-axis and 480 pixels in the Y-axis, this will also be stated simply as 320×480 (and in this case x is the multiplication, or times, sign and not the X-axis!).

To show an image on the display the color of the pixels are set by a program running on the device. Look at the article How Computer Screens and Printers Show Images for more details on how dots make up an image. Because the Android coordinate system runs left to right and top to bottom then plotting a line from 0,0 to 100,100 results in a line that slopes down from the top left of the screen, compared to one that slopes up from bottom left on a normal maths chart.

To get a idea of the variety of screens seen on Android devices look at the article Example List of Android Device Screen Resolutions and Sizes (which also shows that the various screen resolutions are given names). Continue reading

AdMob Ad Incorporated into an Android Activity

A Tutorial on Adding an AdMob Ad to an Android App

Displaying advertisements (ads) is one way of monetizing an App. To monetize (monetise) something is turn turn it into cash. That term applied to Apps and web pages refers to getting revenue through ads or paid content. Showing ads is one way of generating an income from the time and effort spent developing the App. Though a reasonably successful App is required to generate worthwhile funds. Other techniques include charging a price for the App and providing additional content within the App for a fee (In-App Billing).

Google makes it relatively easy to include ads into an App as the simple example code here shows. This tutorial should help those who may have found it difficult to get the example provided with the online AdMob documentation to work. It is assumed that your computer is configured for developing Apps using the Eclipse Integrated Development Environment (IDE) (see Set Up Windows for Android Development if not), and that you can create and run a simple App (see Your First Android Java Program if in doubt). All the steps required to get ad serving in your App working are covered. So read on to find out how to add AdMob to Android Apps.

Get an AdMob Account

You get a very small payment for each ad that is selected (clicked or pressed on) from a device that is running your App. So that Google can make that small payment it must identify in which App the ad was selected. This is done by placing a unique Publisher Id in the code that is showing the ads. To get the unique id for each App you need an AdMob account. Head over to http://www.google.com/ads/admob/ and sign up, you will need a Google account to register.

Target SDK Must be 3.2 or Higher

Your App is ready for publishing, lets put in the ad serving code so that when you activate it on Google Play it can (potentially) make you some money. In this tutorial we will add the code to an existing example project, in this case the code that was written for the article Two Line Lists In Android. You can also follow this tutorial but use your own App to add the code. Continue reading

Windows Symbolic Links for Android Installations on the D: Drive

AVDs Failing to Start if Eclipse is Not on C:

At Eye our machines are built for performance, shaving seconds of the program – compile – test cycle saves hours over the month. Machines have a small solid state drive (SSD) for the Operating System (Win 7 x64) and a big hard disk drive (HDD) for programs and work data. So Win 7 is on a C: drive and everything else on a D: drive. All users’ special folders are relocated to D:. For Android development Eclipse is installed with the Android Development Tools (ADT) Plugin onto the D: drive.

A lot of the initial development of an App is done using an Android Virtual Device (AVD). The AVD is set up using the AVD Manager. Once set up an AVD allows an App to be launched onto it via the Eclipse Run or Debug options. Unfortunately on some configurations where the user folders are on the D: drive, an error is reported when an AVD tries to start (even if the AVD Manager successfully created the AVD). A Starting Android Emulator dialog appears with an error message similar to PANIC: Could not open: C:\Users\Name\.android/avd/AVDName.ini.

AVD "PANIC: Could not open:..."  error

When debugging or running Apps ADT is trying to load the emulator from C: when it, and the configuration files for it, are on D:. One solution is to use a NTFS symbolic link, a.k.a a symlink. Setting up a symlink can fix the above error.

Open a command prompt in the user directory on C: (if you relocated all your special Windows folders to D: then there may only be a hidden Appdata folder in the user folder on C:). Use the mklink program to make a hard link to the .android directory on D:. If user John Doe moved all his Users files from C:\Users to D:\Users then the command to make the directory junction would be:

mklink /J "C:\Users\John Doe\.android" "D:\John Doe\.android"

mklink command for symlink (junction)

Now when the ADT plugin is trying to reference .android on C: NTFS redirects the request to D: and the emulator starts correctly.

(The mklink command is not shipped with Windows XP, to create a Directory Junction on Windows XP us the Sysinternal Junction tool.)