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

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