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

Nexus 7 ADB Driver from ASUS Required When Debugging Your App

Why ADB is not Listing The Nexus 7 Tablet

Eclipse Run Android AppWhen using Windows to develop Applications (Apps) for the Nexus 7 using the Eclipse IDE (or Android Studio), the tablet may not seen in the Android Device Chooser dialog when the Run button is pressed. This is because the Android Debug Bridge (ADB), which runs in the background as adb.exe, cannot communicate with the Nexus device. This short article runs through several possible causes, starting with the most likely reason.

The ASUS Nexus 7 ADB Driver is Required

Use the Asus Nexus 7 ADB Driver when Debugging AppsHaving installed the Android SDK the default Google USB driver is not used for Nexus 7 debugging. Instead the ASUS Nexus 7 ADB driver for Windows must be installed. If you open Windows Device Manager, via Control Panel and System (or in Windows 8.1 type device manager at the Start screen), Nexus 7 will be listed with a small yellow exclamation mark. This indicates a driver is not correctly installed.

The SDK Manager program, installed with the Android SDK, has the option to install the Google USB Driver, normally done by default. (If not run SDK Manager.exe and when it has refreshed the list of packages scroll to the bottom. In the Extras folder select Google USB Driver and click the Install Packages button.) The Nexus 7 ADB Driver is not installed via SDK Manager. It must be installed separately.

Asus Nexus 7 Windows Driver Installation Instructions

To install the Nexus 7 ADB driver for Windows first download the driver from the Asus support pages at http://www.asus.com/Tablets_Mobile/Nexus_7/#support_Download_8. Click the USB link, then Global next to Download from and save the zip file to your computer. The Nexus 7 ADB Driver file is called usb_driver_r06_windows.zip (r06 may have increased if the driver has been updated since this post). Extract (copy) the contents of this zip file to a new empty folder on your PC. Open the Nexus 7 device properties in Window’s Device Manager (double-click) and select the Update Driver button. Browse and select the folder with the extracted driver files. The driver will be installed and the Nexus 7 listing in Device Manager will change to Android Phone and Android Composite ADB Interface. The Nexus 7 should now be available to select when an Application is executed in Eclipse.

Checking Other Nexus 7 Developer Settings

The Nexus 7 USB Debugging options are available from the notifications area when you plug the tablet into the computer. Pull down from the left side of the notification area and select the USB debugging entry. If USB debugging is not enabled it will need to be turned on in Settings. Access settings by pulling down on the right notification area and selecting settings (or go into all the installed Apps from the home screen and find Settings). Scroll to the bottom and select Developer options (if not visible see next paragraph), then check USB debugging.

Enabling Nexus 7 Developer Options in Settings

Developer options may not be visible under settings. To make it visible select the About Tablet entry in Settings. In the About tablet screen find the Build number at the bottom of the list. Tap the build number several times (about 7). After about three taps a message appears and counts down, when it reaches zero the Developer options will have been enabled, press the back key to see the new option in Settings.

Switch Nexus 7 USB Connection Modes

Some developers have needed to switch the USB computer connection mode from Mobile device (MTP) to Camera (PTP) to get the Nexus 7 detected by ADB. In Settings select the Storage option. Select the menu at the right hand of the notification area, then select USB computer connection.  Change the connection option.

Other Solutions

If the Nexus is not being seen on the USB port and the PC has been rebooted try another port. Ensure that any third-party Apps that may use the Nexus 7 USB port are not running or have been removed. Finally try searching online help forums such as Stack Overflow (stackoverflow.com).

Pop-up Window in Android

How to Display A Smaller Window on Top of an Activity

The Activity screen is not the only way to interact with the user of an App. A brief message or dialog can be displayed in appropriate circumstances to ask a specific question or get specific input. Android has build in support for such small focused interactions that require immediate attention.

  • The Toast class – to display brief informational only message.
  • The Dialog class, managed by a DialogFragment – to support a flexible input that can display information and can ask for inputs or choices. There are several built in sub-classes including:
    • AlertDialog – supports buttons (from zero to three), list selections, check boxes and radio buttons.
    • ProgressDialog – supports a progress bar or wheel and supports buttons because it extends AlertDialog.
    • DatePickerDialog – supports selecting a date.
    • TimePickerDialog  – supports a time selection.
  • The PopupWindow class – allows a View to float on top of an existing activity. Suitable for custom informational messages.

These classes build their user interfaces through class methods with support from custom layouts when required. This article looks at using the PopupWindow class. What is the PopupWindow? The Android developer documention has the following class overview:

“A popup window that can be used to display an arbitrary view. The popup window is a floating container that appears on top of the current activity.”

It can be used to display extra information without needing to code another Activity. An example would be to show results at the end of a game (or end of a level), which we will be doing in the following tutorial. The steps for this example code are:

  1. Create a new project.
  2. Design the pop-up window.
  3. Add the code to load and populate the pop-up window.
  4. Call the code.

Open a Project to Add the Pop-Up Window

In this tutorial we are assuming that you have a working project in Eclipse to use as a base, either open an existing project or create a new one (if you need help see Your First Android Hello World Java Program).

Design the Layout for the Pop-Up

For this example we are going to have a pop-up to display a game’s result as gold, silver and bronze medal positions. The pop-up will have a graphic (ImageView) for each of the medals, a TextView for the winner’s name and one for the score. The images for the medals came from Open Clip Art Library user momoko. They have been resized for an Android project and you can download medals_png.zip ready for importing into a project.

Gold Medallion Silver MedallionBronze Medallion Continue reading