Android Bitmap Loading for Efficient Memory Usage

Load a Bitmap from Resources Correctly

When handling bitmaps it is not long before Android developers come across the error “java.lang.OutOfMemoryError: bitmap size exceeds VM budget“. This usually occurs when the bitmaps are large (several megabytes uncompressed),  or running the code on older devices, or trying to load lots of bitmaps. This occurs because Android was design for mobile devices with limited resources, including memory, and bitmaps can require large amounts of memory. Despite Android not dealing with multi-megabyte bitmap loading automatically it can still be done. Instead of loading the whole bitmap a reduced resolution version is loaded (via a technique called subsampling). Android bitmap loading is achieved via the BitmapFactory class. The Options settings passed to the class can reduce the size of the bitmap, saving on memory usage.

Bitmaps can be BIG but Android Screens are Small

A digital image from a camera can be between 5 and 18 megapixels (MP) in size, depending upon the camera or device. This is the uncompressed size. The actual file storing the image, usually a JPEG file, is smaller than the displayed image because of compression. High end cameras can produce 20 MP or higher images. A 5 MP image can have a resolution of 2560×1920, that is greater than high definition (HD) television at 1920×1080, and bigger than the resolution of the Goggle Nexus 10 tablet device at 2560×1600. What about a 18 MP image? A size of 5184×3456!  A Nexus 5 phone has a HD screen, so why load more than 2 MPs of data if the screen can only display a maximum of 2 MPs. By using subsampling the huge photo image being viewed on the Android device only consumes as much memory as required to display it, 2 MP for a HD resolution screen. This saves precious App memory and reduces the possibility of out of memory errors. Here’s an example of loading large bitmaps on different Android devices. A 1000×1000 placeholder image was loaded into an ImageView  and the App run on two devices. One with a HVGA, 320×480, screen and another with a QVGA, 240×320 screen.

Android Bitmap on Different Screens

On the HVGA screen the 1000×1000 image is shown at 320×320, on the QVGA screen it is shown at 240×240. So the one million pixel image only requires a hundred thousand or sixty thousand pixels for actual viewing on these devices. Loading only the required size for display makes sense. On the Android Developers website there is an article on Managing Your App’s Memory and in the section Avoid wasting memory with bitmaps it states: “When you load a bitmap, keep it in RAM only at the resolution you need for the current device’s screen, scaling it down if the original bitmap is a higher resolution.

Android Bitmap Loading Code from the Developer Site

There is a series of lessons on the Android Developers site called Displaying Bitmaps Efficiently that deal with correctly loading, caching and processing bitmaps. When processing multiple large bitmaps it needs to be done away from the User Interface (UI) thread using AsyncTask, with the use of caching when appropriate. There is a sample App for the lessons, DisplayingBitmaps.zip, for Android Studio, though the code can be used in Eclipse if that is your preferred development platform. The example App was previously called Bitmap Fun from BitmapFun.zip. The basic steps in loading a large bitmap are:

  1. Determine the required size (from a known size or determining the size of the target View).
  2. Use the BitmapFactory class to get the bitmap’s size (set inJustDecodeBounds in BitmapFactory.Options to true).
  3. Using 1. and 2. calculate the subsampling value (a multiple of 2) and pass it to the BitmapFactory.Options setting inSampleSize.
  4. Use the BitmapFactory to load a reduced size bitmap.

The following section takes the code from the Android Developers article Displaying Bitmaps Efficiently to provide an example App performing the steps listed above.

Sample Code to Load an Android Bitmap from a Large Resource Image

J. M. W. Turner The Fighting Temeraire A large bitmap is needed. You may be reading this because you have a very large bitmap causing out of memory errors. Here a large image of a Turner painting is used. The image size is 5684×4226, a 24 MP image! You can grab the image from Wikimedia Commons, it is available in several sizes.

An Android App project was created in Eclipse. The large Turner image was added to the project in a folder called drawable-nodpi under the res folder. A large placeholder image (large enough to match the screen width) was also added to the folder. It can be generated from Placeholder Graphic at openclipart.org. The layout is just an ImageView with a Button below it:

Here’s the code for the App:

And the App in action:

Large Android Bitmap Loading

Using a Open Source Library to Manage Large Bitmap Loading in Android

This code is good for a single bitmap, but the Android Developers article goes on to talk about caching and background loading. One way of achieving this is to use an existing implementation, such as provided in the Display Bitmaps sample or existing libraries that support large bitmap loading with caching, including android-query (AQuery),  Android Volley for loading images over networks and Android Universal Image Loader.

Related Article

How to Get a View Size in Android

List of IDEs for Android App Development, Which is Best for You?

Eclipse Alternatives for Android Application Development

An Integrated Development Environment (IDE) is an all-in-one solution that allows an application (app) developer (a.k.a. programmer) to perform the software development cycle repeatedly and quickly. That cycle is to design, write (or code), compile, test, debug and package the app software. For Android app development Google currently supports two IDEs (but read on for a list of alternative IDEs and languages):

  1. Android Developer Tools (ADT) – http://developer.android.com/sdk/index.html
  2. Android Studio – http://developer.android.com/sdk/installing/studio.html (in beta)

Both of these IDEs require the use of the Java computer language to write Apps. The first option uses the well established Eclipse IDE. The second option is based upon the IntelliJ IDE.

The Google IDEs and the Java language are not the only options for Android App development. Some developers might not need the power of Java or just don’t get on with C style languages. Some developers would like a single code base to support other platforms: Apple (iOS), Windows, Blackberry and the Web (HTML5). This is known as cross-platform development. Well there are plenty of alternatives to Google’s tools, see the following table for a list of Android app development IDE and computer language alternatives. Code can be written in different languages, like BASIC, HTML5 or Lua. Many of the alternatives are free to use, some open source, some restricted versions of paid for products. A few may not have a free version. Some will require the Android Software Development Kit (SDK) that comes with the Google tools to be installed. It is possible to install several IDEs onto the same computer to try them out.

List of Alternative Android App Development IDEs

Name Language C-P URL
AIDE (Android IDE) HTML5/C/C++ Yes http://www.android-ide.com/
Application Craft HTML5 Yes http://www.applicationcraft.com/
Basic4Android BASIC No http://www.basic4ppc.com/
Cordova HTML5 Yes https://cordova.apache.org/
Corona Lua Yes http://coronalabs.com/
Intel XDK HTML5 Yes https://software.intel.com/en-us/html5/tools
IntelliJIDEA Java No https://www.jetbrains.com/idea/features/android.html
Kivy Python Yes http://kivy.org/#home
Lazarus IDE+free pascal+LAWM Pascal Yes http://www.lazarus-ide.org/, http://www.freepascal.org/, LAWM
MIT App Inventor Blocks Yes http://appinventor.mit.edu/explore/
Monkey X BASIC Yes http://www.monkeycoder.co.nz/
MonoGame C# Yes http://www.monogame.net/
MoSync HTML5/C/C++ Yes http://www.mosync.com/
NS BASIC BASIC Yes https://www.nsbasic.com/
PhoneGap HTML5 Yes http://phonegap.com/
RAD Studio XE Object Pascal, C++ Yes http://www.embarcadero.com/
RFO Basic BASIC No http://laughton.com/basic/
RhoMobile Suite Ruby Yes http://www.motorolasolutions.com/US-EN/Business+Product+and+Services/Software+and+Applications/RhoMobile+Suite
Telerik HTML5 Yes http://www.telerik.com/platform#overview
Titanium JavaScript Yes http://www.appcelerator.com/titanium/titanium-sdk/
Xamarin C# Yes http://xamarin.com/

Table Notes:

  1. C-P, Cross-Platform, if No only Android supported, if Yes supports App production for other platforms (you will need to check if your required platform is supported).
  2. Language, HTML5 also includes the related technologies of Cascading Style Sheets (CSS) and JavaScript.
  3. AIDE and RFO Basic allows code to be developed on the go on Android devices. The code can be packaged into full blown Apps.

Support for Android Programming

This above list of free and commercial IDEs for Android shows that other languages can be considered when wanting to develop apps. Some of these Android options provide cross platform development from the same app source code. (For some IDEs the Android SDK will need to be installed.) Purchased commercial Android development packages will come with varying degrees of support from the company and the user base. Open source and free packages will be supported by the user and development community, and sometimes paid for support is available. Forums are a useful source of answers for Android development issues.

Microsoft are developing Cordova support for Visual Studio, see Microsoft’s Multi-Device Hybrid Apps web page.

Android NDK

Google provides for free the Native Development Kit (NDK) that allows programming in C or C++, see the Android NDK page for more information. Use the NDK to optimise time critical portions of an App. Google does not recommend it for general App development.

Setting Up Google’s Android IDEs

If you need help installing Eclipse or Android Studio see our articles. For a quick Eclipse set up see:

For Android Studio set up see:

For a step-by-step set up of Eclipse see:

Please let us know of any other Android development options you come across. It would be interesting to hear of any App successes from using any of the above packages, drop us a line at dan@tekeye.biz.

Android Menu Vs Action Bar with Example Code

An Android Menu in Your App

When a new Android App project is created in the Eclipse or Android Studio IDEs there is the option to create a default activity (the Create Activity option in the New Android Application wizard). If the option is checked and Blank Activity is chosen a simple App ready to run is generated. This App simply shows the message Hello world! on the device screen (see Your First Android Hello World Java Program).   This simple App has a menu with one item called Settings. On devices with a physical (hardware) menu key, the Settings menu option appears at the bottom of the screen, when the key is pressed:

Basic Android Menu Option

On devices without a hardware menu key, Android Version 3.0 and later devices (API level 11+), an icon in the Action Bar shows the Settings menu item. This icon is referred to as the action overflow. However, due to it’s stacked appearance in this article it will be referred to as the menu icon:

Action Bar with Basic Android Menu

The above two screens show the older Android menu vs Action Bar menu, i.e. pre-Honeycomb using the physical menu key, and post-Honeycomb menu using the Action Bar icon (3 small stacked boxes icon know as action overflow). Further differences in use are examined in this article with code examples. Here is the code for this basic App: Continue reading

ERROR Unable to load VM from snapshot, Android AVD

An Error Occurs Starting an AVD That Previously Worked

When coding and running an App in the Eclipse Integrated Development Environment (IDE), debugging can be performed on an Android Virtual Device (AVD). You may see ERROR Unable to load VM from snapshot, one solution is to clear Launch from snapshot in the AVD Launch Options dialog, Note changes saved to the AVD will be lost. To access the launch options start the AVD from the Android Virtual Device Manager.

Error Unable to Load VM from Snapshot Android AVDThe error can occur with an AVD that previously ran without problems. It usually occurs after updating the Android Software Development Kit (SDK), via the Android SDK Manager program. It can also occur if the AVD configuration has been changed using the Edit option in the SDK Manager. When starting the AVD, or when pressing the Run button which attempts to start an AVD, the Starting Android Emulator dialog shows, it displays this error message (where Name-of-AVD is the chosen AVD): Starting emulator for AVD ‘Name-of-AVD’ emulator: ERROR: Unable to load VM from snapshot. The snapshot has been saved for a different hardware configuration.

If the virtual hardware upon which the emulator executes has changed then the saved virtual machine (VM) snapshot is no longer compatible with it. The virtual hardware can change if the hardware image has been updated by a new release of the Android SDK (updated by the SDK Manager), or the AVD configuration has been edited.

Fixing Error Unable to Load VM From Snapshot

Android Virtual Device Manager IconA possible solution is to start the AVD fresh and not from a saved snapshot. Open the AVD Manager. Select the problem AVD from the list of existing AVDs. Select the Start button and the Launch Options dialog appears.

AVD Clear Launch from snapshotClick the Launch from snapshot check box to clear the tick before clicking the Launch button. The AVD starts from a fresh virtual machine image. Changes previously saved on the AVD are lost.

Occasionally you will still get an error launching the AVD. Delete the configured AVD and recreate it. (See Managing AVDs with AVD Manager.)

Supporting Multiple API Versions in Android

Writing Code for Different API Levels

How do you handle changes in the Android Application Programming Interface (API) in code? By placing code that uses changed APIs into a separate class, then wrapping the use of that class in a test. The test is comparing the device’s API level against the code’s target API level. The Build class provides the relevant version numbers to use in the test. However, there are other considerations in supporting multiple API versions. These factors are explored in this article.

Android Robot Logo in the Supporting Multiple API Versions ArticleNew versions of Android provide new classes, additions to existing classes and deprecated classes and methods. (Deprecated classes and methods are those that are no longer required and will be removed in future releases.)  These changes are due to the Android platform continuously evolving to take advantage of new hardware, new ideas and to improve performance.

Reference Documentation API Level Filter

The Android Reference documentation has details on all the classes in all the APIs. Each part of a class has a label to denote in which API level it first appeared. The API documentation can apply a filter based on API level to grey out the classes and parts of classes that were not available prior to a give API version.

Supporting Multiple API Versions in Android

The Android API Differences Report

To see an overview of the changes between an Android API level and the previous API release view the Android API Differences Report. The report is viewed online at the Android Developers web site. The address is http://developer.android.com/sdk/api_diff/X/changes.html where is the API level to examine the differences from the previous level. For example if X is 9 then the differences report show the changes from API level 8 (Froyo) to API level 9 (Gingerbread). A link to each differences report is in the post Android Versions Numbering and API Levels.

Reading the Android Devices API Version

The API version used by an Android device is read from the static Build class in the android.os package. The Build.VERSION.SDK_INT returns the API level. The various API levels are defined in Build.VERSION_CODES.

For example here is some code to test for API level 9 (the first Android Gingerbread release):

The App running this code must have the minSdkVersion attribute in the manifest (AndroidManifest.xml) set to 4 (Donut) or higher. Prior to API level 4 SDK_INT was not available, it was Build.VERSION.SDK, a string. There are very few devices around early than API level 4 so setting the minSdkVersion to 4 or later should not be an issue, however, a workaround is discussed later.

Detect Other Android API Levels

The above code is easily extended to detected other API levels. So to detect API level 8, Froyo, the code becomes: Continue reading

HTML5 in Android App for WebView Display

Load HTML Page Saved in Android Project

To display lots of informational text and images in an Android Application (App) HTML is a good choice. HTML is now at version 5 and supports text formatting and image display. The formatting of the text can be enhanced by applying CSS (Cascading Style Sheets). This article shows how to add HTML5 in Android using a simple example. The HTML file is created in an editor. The file is placed into the assets folder. An App with a WebView loads the HTML using the URL file:///android_asset/file.html, where file.html is the file created.

Although this tutorial will be loading a static HTML file the WebView can also display dynamic HTML by using JavaScript and the Document Object Model (DOM). The combination of HTML for page elements and structure, CSS for formatting, DOM to access the structure and JavaScript for manipulation makes the WebView a powerful component for displaying large amounts of text and images in an App.

Create Files for HTML5 in Android App Example

To start the HTML5 in Android tutorial create a new Android App project in Eclipse or Android Studio (if you don’t know how see our Android Hello World Java Program example). Here the project is called Show HTML. The HTML to be displayed in this example will be an image and some text.

Crocodile image for the HTML in Android App exampleA new file is created in the projects assets directory. In Eclipse use the File menu to select New and then Untitled Text File. Enter the required HTML. (To see the basic structure of a HTML document look at the article Hello World in HTML.) In this tutorial the text used is a poem by Lewis Carroll from the book Alice’s Adventures in Wonderland. Any text can be used. The image of a crocodile was from the Open Clip Art Library and is in the Public Domain. Copy this image and save it into the assets directory as crocodile.png. Finally here’s the full text for this HTML example:

Copy this HTML to the new file, save it in the assets directory and call it crocodile.html. (If using Android Studio you will need to create the assets directory under main in the project tree and name the HTML file first before adding the text.) Continue reading

Android Debug Vs Release Build Check in Running Code

Distinguishing Android Debug Mode Vs Release Mode

Your Android application (App) will execute in debug mode in you development environment (e.g. the Eclipse or Android Studio IDEs), and it will execute in release mode when installed from Google Play. In release mode any debug logging, StrictMode and the debugging option must be disabled. You can wrap the logging calls and StrictMode set up in code that checks for debug mode. To detect Android debug vs release mode there are two objects that expose a debug flag, ApplicationInfo (since API Level 1) and BuildConfig (recent SDK releases).

Android Debug vs Release Using ApplicationInfo Flags

With ApplicationInfo the flags field has a debug bit. It is set via the android:debuggable attribute on the application element in AndroidManifest.xml. Usually the android:debuggable attribute does not need to be present, it is set automatically by Eclipse or Android Studio. The IDEs set it to true to allow the App to be debugged. It is set to false to turn off debugging when the final APK is generated. To override the default settings add android:debuggable to the application element. Set it to true or false as required, e.g.:

To use it perform a boolean And on flags with ApplicationInfo.FLAG_DEBUGGABLE, if the result is not zero the App is in debug mode.

Android Debug vs Release Using BuildConfig.DEBUG

BuildConfig.DEBUG is set true when the App is running in the IDE. It is set false in the released APK unless android:debuggable is present and set true. Therefore  BuildConfig.DEBUG reflects the android:debuggable value unless android:debuggable is set false and the App is running in the IDE, in which case it will still be true. See the table later in the article. Continue reading

Android Icon Size – Launcher and Google Play Store

What is the Android Icon Size for an App?

For Android launcher icons you will need 6 sizes of PNG or JPG files. In pixels these are 48×48, 72×72, 96×96, 144×144, 192×192 and 512×512. The first five are for the App and the last one for when the App is deployed to the Google Play store. These are the final size of the icons and you must allow for a small margin, hence the area the icon is drawn in will be a bit smaller. For low density screens Android halves the 72×72 icon, but it is possible to include a 36×36 icon in the App for completeness, making 7 icons in total. An Android icon size table in this article summarizes all the relevant information.

144x144 XXHDPI Android Icon Size96x96 XHDPI Android Icon Size72x72 HDPI Android Icon Size48x48 MDPI Android Icon Size36x36 LDPI Android Icon Size

Android Screen Densities

The number of dots (pixels) per inch that an Android device’s screen holds determines how sharp the image on the screen looks. The more Dots Per Inch (DPI) the sharper the image. Android groups screen densities into several classes, medium, high, extra high, extra extra high and extra extra extra high! These are referred to as MDPI, HDPI, XHDPI, XXHDPI and XXXHDPI. There is also a low density class, LDPI, however not many new devices have a low density screen and thus LDPI is no longer important. MDPI is around 160 DPI, HDPI around 240 DPI, XHDPI around 320 DPI, XXHDPI around 480 DPI and XXXHDPI around 640 DPI. (LDPI is around 120 DPI). It is the screen density that determines the Android icon size used.

Android Launcher Icon Name and Location

When a new Android project is created in Eclipse or Android Studio the launcher icon file is called ic_launcher.png. You can choose the Create custom launcher icon option in the New Android Application wizard (New Project wizard in Android Studio). This allows you to configure the launcher icon based on the default Android robot, or an image file, or from several clip art images, or finally from some text. If an icon is not configured the default robot is used. The various size icons are created and placed into a folder in the projects res directory. The folders are drawable-mdpidrawable-hdpi, drawable-xhdpi and drawable-xxhdpi. It you need a low density, LDPI, icon create put a 36×36 PNG or JPG in the drawable-ldpi folder. To support Cupcake devices (API level 3) add a drawable folder and copy the 48×48 PNG or JPG file from drawable-mdpi to it. For the latest highest density displays create a drawable-xxxhdpi folder for a 192×192 icon.

The icon is referenced in the Android manifest. In the projects AndroidManifest.xml file the <application> tag has an android:icon attribute. This is set to @drawable/ic_launcher. The icon file’s name does not need to be ic_launcher, it can be called something else. For example if all the icon files for the various sizes were called my_app_icon.png then the attribute in the application tag could be set as android:icon=@drawable/my_app_icon.

Notice how the reference to the icon only needs the drawable part of the folder name. Android works out the correct density icon to use. Android will also scale one of the other density icons if an icon at a certain density is missing (though that may result in a fuzzy icon being displayed on the screen).

Android Icon Margins

The Android Operating System (OS) has evolved since it was released. This means that the icon requirements have changed over the years. The main changes are the increase in screen sizes and screen densities. Low density and medium density devices were common. Now high density and extra high density devices are the most common.

Previously it was recommend that the icon included a margin around one twelfth of the total size between the edge of the icon and the image it contained. For example the medium density icon is 48×48 pixels, one twelfth of this is 4, giving a margin of 4 pixels around the icon. This means the area available for the image is 40×40 (48 minus the margin of 4 pixels on each side).

However, the bigger screens on today’s devices gives more room for the icons so a smaller margin can be used, for example one eighteenth of the icon size. The margin allows for spaces between the icons on a screen and to allow for any drop shadows or parts of the image that stick out a little.

The High Resolution Application Icon needed for the Google Play store must be 512×512 in size. This image can have a margin to allow for padding or drop shadows, for example it could be 464×464 on the 512×512 canvas giving 48 pixels for padding and drop shadows. Again the size of the margin may depend upon the type of image being used, but the final file will be a 512×512 in size.

Android Bitmap Assets Ratios

With the 48×48 icon as baseline the 6 launcher icons have the ratios 0.75, 1, 1.5, 2, 3 and 4. These ratios apply to the screen densities. So a high density screen (HDPI) is 1.5 times a medium density screen (MDPI). I.e. 1.5 * 160 = 240. Likewise for the other densities. These ratios generally apply to all images used in an App that target different screen densities. If a bitmap is 100×100 on a medium density screen use the ratios to calculate the bitmap sizes required for other densities (75, 150, 200, 300 and 400 in this case). When generating icons and bitmap assets work at a high resolution and scale down, this prevents pixelation of the images. E.g. a canvas of 576×576 or 864×864 is good for design work. An art-board of those sizes is bigger than the biggest icon required (512×512 for the Google Play store). Even better use a vector drawing package such as Inkscape which effectively allows working at any resolution.

Android Icon Size Table

The following table summarizes all the above information.

Android Icon Size and Location for Apps
Density size Location Ratio Screen Margin
XXXHDPI 192×192 drawable-xxxhdpi 4 640 DPI 12 to 16 pixels
XXHDPI 144×144 drawable-xxhdpi 3 480 DPI 8 to 12 pixels
XHDPI 96×96 drawable-xhdpi 2 320 DPI 6 to 8 pixels
HDPI 72×72 drawable-hdpi 1.5 240 DPI 4 to 6 pixels
MDPI 48×48 drawable-mdpi 1 160 DPI 3 to 4 pixels
MDPI 48×48 drawable (Cupcake) 1 160 DPI 3 to 4 pixels
LDPI 36×36 drawable-ldpi 0.75 120 DPI 2 to 3 pixels
NA 512×512 Google Play NA NA As required

You will find a few icons on the Android Graphic Resources page, and of course many thousands more on the web.

For more information on Android Icons see the Iconography web page on the Android Developers web site.