9-Patch Image – Designers Vs Developers

I am sure when the Google team came up with the 9-patch image, they must have felt real smug. Engineers excitedly talking around coffee machines about the pure awesomeness of it’s capabilities must have been a common sight. And in all the excitement they conveniently forgot to write all about it and hoped that designers and developers would miraculously figure out how it worked and more importantly how it didn’t.

Fortunately days have improved and there is now some documentation available at http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch, but I might add that it is the bare minimum.

I have also seen numerous cases where the designers and developers have been at each others’ throats trying to figure out who is responsible for all the screwed up 9-patches. So here’s an attempt at spreading peace and bringing the two at the same page.

Where do I use a 9-patch?

There are many situations where in the backgrounds are same though the sizes of the View elements may vary in size. For example backgrounds of buttons whose size depend on the button text size. Backgrounds for ViewGroups whose size vary based on the content. In such situations, adding multiple backgrounds for each of the elements is pointless.

The image below shows how different backgrounds on the left can be replaced by a single, much smaller 9-patch image and yet achieve the same result.

nine_patch_usability

The Basics

Before we go all technical about 9-patch, here are some basics

  • 9-patch image is a Stretchable Bitmap Image.
  • It has a 1-pixel transparent border on which the stretchable and the static areas of the image are defined using black color.
  • It has an extension .9.png. For example, image.9.png.
  • As of now two things can be defined of the image, the SCALABLE Area and the FILL Area (can be also referred to as the padding of the image).
  • TOP/LEFT borders are used to define the scalable areas while BOTTOM/RIGHT is used to specify the fill area.
  • Multiple scalable areas can be specified for the image.

nine_patch_structure

The image above shows all the Scalable and Fill areas. You might find it a little confusing in the beginning but by the time you are done with this, it will all make sense.

The 9-patch structure

Basic structure showing the scalable areas

Basic structure showing the scalable areas (Image scaled from original size to show the patches clearly)

This shows the basic structure of the 9-patch. You will observe that there are 9 divisions and hence the name 9-patch. The four corners remain static and do not scale in any direction. The center-left and center-right areas scale only along the Y-axis while the top-center and bottom-center stretch only along the X-axis. The center of the image stretches in both the X and Y directions.

Creating a 9-patch Image

Below are the steps to create a 9-patch image using Photoshop or any other image editing tool such as GIMP because I am sure most designers would be using one of them. Developers on the other hand wouldn’t. Click here if you are a developer and want to use the Draw 9-Patch tool.

1. Let us say that we want to make an image that is 48×48. So we start of with an image of the size 48×48.
2. Now we add a transparent border to this image. As a result the size would now be 50×50.
3. Next we use a pencil/pen tool with size 1 pixel, select the color as black and mark along the top and left borders to specify the area that we want to scale. You should end up with an image similar to the one shown above.
4. Finally specify the fill area by marking along the right and bottom borders.

Scalable Areas

Here are a couple of examples demonstrating how different scalable areas result in different types of scaling.

Single section that stretches in both directions

Single section that stretches in both directions

In the example below you will notice that, we have marked multiple patches on both left and top borders. As a result we now have 9 static areas, 12 partial stretchable areas and 4 complete stretchable areas. This helps us in cases where we don’t want certain parts of the images to be scaled. You can see how the red dot has remained uniform, no matter how it is scaled. In the previous case, the red dot was getting scaled along with the image size.

Multiple sections that stretch in both directions

Multiple sections that stretch in both directions

Fill areas or Padding

The purple section specifies the content area

The purple section specifies the content area

We now look into the area which the Android docs say is optional, though doesn’t clearly mention what the side effects would be. The Fill area can be specified by drawing black lines along the right and bottom borders. The content is restricted within the area specified by these lines. In the adjacent image, the area marked by the intersection of the left and right lines will be the content area of the View whose background is set with this 9-patch image.

The docs say that if these “optional” lines are not specified, then Android uses the top and left lines to define the fill area. Can you imagine how catastrophic the result would be in one of the example above? Well fortunately there is a way to deal with such cases but unfortunately it is not mentioned in the docs. You can see the “For the developers” section below for cases where the padding lines are not provided.

Points to Remember

Now that you know what 9-patch images are and how they are made, here are a few points you must keep in mind before you start.

  • 9-patch images can scale up but not scale down. Scaling down results in visual artifacts.
  • Always design for the smallest size possible. This will increase its re-usability.
  • If the Fill Area is not specified, then Android uses the top and left lines to define it. This may lead to visual artifacts.

For the Designers

  • The transparent border MUST be absolutely transparent and the border lines MUST be absolutely black ie #000000.
  • While resizing 9-patch images, remove the border, re-size it and then add the border. If you use an image editor to create and resize 9-patch, then antialiasing can ruin your image.
  • Android prefers that the ‘intersection zones’ are 1×1 pixel size for proper scaling. For bigger zones, the scaling could lead to visual artifacts.

For the Developers

  • If the Fill Area is not specified, there maybe abnormal behavior. In such cases, always specify some padding. And if you don’t require padding then use “padding=0dp”.
  • Put your 9-patch image in the /res/drawable folder to use for different densities and screen sizes and make sure they have “.9.png” extension.
  • If you are using the same 9-patch for different densities, then be cautious. The static areas will appear different based on the density. Make sure you check them on real devices and then decide if you require separate images for separate densities.
  • Do not use a 9-patch image that is bigger than your View.

Android ViewTree and DecorView

The Graphical User Interface forms an integral part of the Android application development. The UI not only acts as a mode of input for the user but also as a mode of feedback from the application based upon an action performed. It is therefore very important that a developer understands how the UI is created and updated.

ViewTree

The basic components of the visual UI is the View and a container called ViewGroup which contains a collection of Views. The ViewGroup itself is an extension of a View. The different widgets like the TextView, Button, etc are nothing but extensions of View which are all arranged within layouts, viz. LinearLayout, RelativeLayout. The layouts are nothing but sub classes of ViewGroup. A ViewTree is nothing but the tree structure that is formed as a collection of these views and viewgroups in a layout.

Let’s start with an example. Here you can see that a number of Views and a LinearLayout are all contained within a RelativeLayout which acts as the parent ViewGroup. All of these come together to form the ViewTree.

The tree structure as seen in Eclipse

When you set the view in your activity using setContentView() and run the program, you’ll see something like this.

If you see the xml file and the way each of the views have been drawn, you’ll observe the following.

  1. The ViewTree that is formed is traversed in a top-down fashion.
  2. The parent is always drawn first and then the children, again in a top-down fashion.

So in our example, the RelativeLayout Layout is first drawn, followed by its children WhiteView, RedText and so on, till finally GrayView is drawn obscuring the Views drawn before.

To visualize, how all the views are being drawn, think of the screen as a coordinate system consisting of X, Y and Z axes and the top-left of the screen as [0,0,0]. X extends to the right, while positive Y extends along the length of the screen. Z extends out of the screen. However do not confuse this system with the coordinate system of the Sensors of the phone.

The View Layout structure and their z-order

So the Views are basically placed along the positive Z axis as we move down the tree. Note that the Android drawing mechanism takes care that it does not draw parts of Views which are hidden by Views placed with greater z-values.

Now that we know how the Views defined by us in the xml are drawn, let us see if this all that there is in the View Tree. For this, we need the help of a tool known as the “heirarchyviewer” in the android installation folder under android-sdk/tools. Before we can use this tool, first run the program in the emulator or the device. Use the commandline to navigate to the folder and start the heirarchyviewer.bat file.

Shown below is the snapshot of the hierarchy viewer.

In the hierarchy viewer, the columns represent the depth of the tree while the number of rows in each column represents the breadth at each level. So you will notice that our RelativeLayout is not really at the root level but is in fact a child of a FrameLayout called “content”. The call to the setContentView(View v) basically sets the View v as the content view.

TreeView heirarchy of an Activity with a TitleBar

Now notice the column containing the FrameLayout “content”. It has a sibling which is another FrameLayout containing a TextView. This is nothing but the Title Bar of the Activity. Let’s see how the View Tree changes if we the titlebar is removed. Go to the manifest file and add the following line to thetag

android:theme="@android:style/Theme.NoTitleBar"

On running the hierarchy viewer, you will notice that the structure has changed. The content view now has just the “content” FrameLayout whose parent is the PhoneWindow$DecorView.

TreeView of the Activity without the TitleBar

Let us take a look at the PhoneWindow and the DecorView.

DecorView

PhoneWindow is the only implementation of the abstract “Window” class which provides the policies defining the look and feel of a window. It forms the top-level window which together with the WindowManager helps in setting the background, title area (either with TitleBar, ActionBar or a user specific custom title bar) and default key processing. The overall window properties can be customized using the WindowManager.LayoutParams.

The DecorView is a private class of the PhoneWindow which is nothing but an extension of FrameLayout. This is the class which forms the top-level application view. Based upon the settings provided in the Android Manifest regarding the themes or the flags set in the PhoneWindow on what type of a window we need to create, the layout of the DecorView is created. So for our example, in the first case, we had a simple theme containing containing a title bar and the contentview. The Phone Window generates a layout that consists of a linearlayout with the title and a framelayout where the contentview can be set. In the second case, we specified that we did not need a titlebar and hence it created the decorview with just the framelayout where the contentview can be set.

Conclusion

So here’s a brief of how the View Tree is generated when a Activity is started,

  1. The PhoneWindow generates a layout for the DecorView which forms the root view based upon the theme provided in the manifest file or otherwise specified using the Window interface.
  2. The activity’s setContentView() is used to set the layout xml as the content view. This internally calls the PhoneWindow’s setContentView().
  3. Now everytime the UI is refreshed the View Tree is traversed as mentioned earlier.

Note: If you plan to use a custom title bar using FEATURE_CUSTOM_TITLE, note that calling setContentView() for the first time or getDecorView() fixes your decorview and you can no longer change many window characteristics. Keep this in mind while designing.

Custom Control – Extending Existing ViewGroups

In the previous post we saw how we can extend an existing View to enhance its properties. In the following post, we go a step ahead and extend one of the existing layouts, put in a few controls and turn it into a widget.

Introduction


Here’s an use case, where you need a reusable component called the ProgressTracker, which basically consists of a TextView, an ImageView, a ProgressBar and a Button.The function of the ProgressTracker is to show a Text saying what it is that you are doing, an Image to denote the state of the task and a button that the user can use to perform any action by attaching an OnClickListener() to it.

Requirement

  1. We should be able to rearrange the inner components through xml based upon our need.
  2. The imageview and textview are optional but the rest must be provided.
  3. The ProgressTracker must be inherited from RelativeLayout which will give us more flexibility in arranging the child components.
  4. It should be generic and reusable.
  5. The user should be able to decide what happens when the button is clicked.
  6. The user should be able to know what the state of the ProgressTracker is, ie, if the task has not started, in progress, successful or failed.

Implementation

To stay within the scope of the tutorial, I’ll focus only on the concerned code snippets. You can however go through the complete code to get an idea about how the ProgressTracker can be used using the sample project given at the end of the post.

We begin by extending the RelativeLayout and implementing the constructors. In it, we extract the styleable attributes which we define in the attrs.xml. As the progress bar and the button are not optional elements we extract their ids and check their validity. Incase, either of the component is missing we throw an exception. I am not going through the extraction details as I have already explained it in Custom Controls – Extending Existing Views.

attrs.xml
Based upon our requirements we have four attributes that specify each of the components in the widget.

activity_main.xml
The ProgressTracker can be used in the following manner. Each of the components are defined inside the ProgressTracker and also assigned to their respective roles within the widget.

Constructor of ProgressTracker.java
Do not worry about the resetProgressTracker() method. You can see the complete code to see its implementation.

Next, override the protected onFinishInflate() method which is called once the view and all of its children have been inflated from the xml. Now find the views by their ids.

Once we have the views, we now must delegate a few methods from the child components to the ProgressTracker so that they can be set up from outside using the ProgressTracker object. Lets override the following methods

  • setText(String text)
  • void setMax(int max)
  • int getMax()
  • void setProgress(int progress)
  • int getProgress()
  • void incrementProgressBy(int diff)
  • void setButtontext(String str)
  • void setActionButtonOnClickListener(OnClickListener l)

Apart from these we also add a few new methods to support error notification and status management of the progress tracker. Implementation of all the methods can be found in the sample project code.

As I have mentioned earlier, the imageview and the textview are optional. The textview is standard, so there is not much to explain. However, you need to pay attention to the ImageView.

The ImageView is used to show a separate image based upon the status of the ProgressTracker and there are 4 status as mentioned above. To display the 4 states, we use a level-list drawable that has 4 drawables corresponding to each state. Here’s how it looks. Make sure to set a level-list drawable to the ImageView src for proper functioning. Here’s what a level-list drawable looks like

task_status.xml

We will see the level-list drawable in details in another post.

The corresponding code handling the ImageView in the ProgressTracker is shown below

Here’s a little snippet from the MainActivity which shows you how the ProgressTracker can be used. See MainActivity.java for various combinations and complete implementation.

That is pretty much it. The magic is mainly in the attrs.xml, the constructor and the onFinishInflate() method. If you understand these 3, you will soon be extending the different layouts to make your own reusable components. The rest of the code is to give the ProgressTracker it’s functionality.

In the sample project, I have used 3 different ways the same ProgressTracker can be used. That is the beauty of it. The user is absolutely free in arranging the components in anyway they want. I have unfortunately been unable to make the UI too jazzy for now :P

You can view and download the complete working code here.

Custom Control – Extending Existing Views

Building on our previous example of how we can extend existing controls and customize them for our requirements, we improve the “CustomFontTextView”. In the last post, we saw that by extending a TextView and then setting it’s font in it’s constructor we can achieve a TextView with custom fonts. But you will soon see that it rather restricts our development. If we were dealing with a number of different fonts, we would have to replicate them in multiple classes and then use each of them.

What we need is a more generic approach to the problem. As a developer, one should always build his own toolkit of reusable components over time which speeds up development. We could make it more generic if there was a way in which we could specify the font type at the time of defining the xml. This is possible by declaring an attribute through styleable which could be accessed through the xml.

So the basic steps are as follows

  1. Declare an attribute in a styleable which will be used to specify the font type.
  2. Add your custom fonts in the assets/fonts folder.
  3. Use the specified font type in the constructor of your extended TextView to access the custom fonts.

Let’s start with the styleable. In the “res/values” folder, we add a resource file called attrs.xml. This is the file where all our attributes of our custom controls go. In it we add the following piece of code.

We declare a styleable name “CustomFontTextView” and within it declare an attribute called “fontName” of type “enum”. In our example, we have four different font types which we have specified using name/value format.The attributes can be of different types such as integer, string, boolean, etc. We will discuss styleables in more details in another post.

The next thing we need to do is to access the attribute in our extended class. Check out the updated code of the CustomFontTextView below.

We declare a TypedArray which points to an array of values retrieved with obtainStyledAttributes(). We will look into it in more details at a later time. For now, we need to extract the fontName using the getInteger() of the TypedArray. We also pass a default value (-1 here) which is returned in case we don’t find a valid value in the array.

Note that it is important to call recycle() on the TypedArray so that the array can be cached for later use. A lot of people ask about the purpose of recycle() and why it is recommended. If you look at the code of TypedArray, you will realize that it is basically a caching mechanism which stores the currently retreived StyledAttributes for later re-use.

Once we retreive the fontId which is nothing but an enum value for the font name, we load the appropriate font type.

Finally, we need to use this in our xml files and specify the font. The code below does just that

The implementation is pretty straight forward. You need to add the xml namespace of your custom control.

where “app” is the name we have assigned here to represent the namespace.

It can either be added at the top level viewgroup affecting the complete xml or just within your custom control. To specify the CustomFontTextView, you must specify the complete qualifying name. In this example, it is com.iwannalearn.customcontrols. CustomFontTextView. See what happens when you just specify CustomFontTextView. Check out the error that occurs.

To specify the font name, you must use the namespace:attributeName format. Ex, app:fontName = “AirMole”.

And that’s it! You are done. Compile and run it. If you have done things correctly you will see a screen similar to the following, with fonts specified by you.

Custom Fonts ScreenShot

Note: If you want to make it more generic. You could use a “string” format instead of “enum” and pass the name of the font to the CustomFontTextView. You can then use this name to open the appropriate file. Another thing that you can do to make it more efficient, is to create a spearate file which inflates the font file from the assets folder and keeps a reference to it. In that case, you can save re-inflation time, specially if you are using the CustomFontTextView in numerous places in your application.

You can view and download the complete working code here.

Custom Controls – An Introduction

Introduction

Very often while developing for Android, you will come across situations where you need a control which is not readily available in the default set of Android controls. However, Android was developed keeping the developer in mind, so that the developer’s creativity is not inhibited by the platform. All you need to do is just find out what and how to do.

There are a number of approaches which you can take to make a custom control, the choice however will depend on what you want and its level of complexity. The general approaches that you can take are as follows,

  1. Extend an existing View type or a widget. Pretty simple job here. Check if you have some existing View in the framework, extend it, implement the extra functions you require and you are done.
  2. Extend an existing ViewGroup (any layout) and put the controls you require in it. Add the extra functionalities and you are ready to reuse it in other places.
  3. Extend the class View/ViewGroup and implement everything. This is a little advanced and you would require a little extra knowledge of the way Android draws and creates layouts but this is the father of all customizations. With this method you can make a control that is as unique as you.
  4. Implement extra interfaces to existing Views/ViewGroups such that it can handle more events and do more. This is similar to 1 and 2, with the exception of implementing interfaces.
  5. Reuse the Google code of an existing widget and change its behavior. This might sound like a hack but you have to agree that there are times where you have looked at a control and thought, “if only…”. Eg, If only I could interchange the position of the RadioButton and its text. In some cases, it can be done by extending it but at other times, the behavior is so in its core that you need to reimplement it. At such times, its better to reuse the code than reinvent the wheel. There are 2 positives in this.
    • You see some really good code and learn from it.
    • Once you learn to figure out the way google writes code, you can quickly change it and come up with just the right control in quarter of a time.

I’ll be covering each of the cases, in following posts but for now, here’s a small introduction into how custom controls can make your life easier.

First Custom Control

When I first came across the requirement of setting fonts to my Textviews I was shocked to see that I could not set it through xml. The only fonts you can set using xml are the default android fonts. I knew how to go about it programatically but can you imagine the pain of setting it for every TextView in every file in the project?

The most natural thing to do was to extend the TextView and set the font in the constructor.And that is simple.

First, make a folder called “fonts” in the assets folder and put your font in it. In the example I have put the airmole.ttf file.

Next, extend TextView and in it’s constructor load the font and set it using setTypeface() and you are done.

If you are wondering what the isInEditMode() does, then just comment the check and observe what happens to your graphical view of the xml in Eclipse. You will mostly see the following error,
The graphics preview in the layout editor may not be accurate: Typeface.createFromAsset() is not supported.

What the check basically does is that it avoids the code within it when you are viewing your xml and hence falls back to the default TextView. This helps in designing as you can actually see the content of the TextView.

Here is the xml file where the CustomFontTextView has been used.

Note that the CustomFontTextView requires it’s complete qualifying name. Just specifying CustomFontTextView> will not work.

JSON Parser tutorial for Android using JSONObjects

Introduction and sample data


JSON is currently one of the more widely used formats for data exchange between various languages and services. While developing for Android, you will often come across situations where you would be required to parse JSON responses from servers. We will use the following example available at the JSON site.

The JSON data shown above has numerous nested objects, name-value pairs and also an array.

Data Analysis


Just a low down on JSON before we begin implementing the parser. JSON is basically a collection of nested name-value pairs where the names are strings and the values could be strings, integers, doubles, objects, etc. (Of course, represented in a string format). Analyzing our sample data will give us a clearer idea.

Each object is encapsulated in {…}. So here the outermost set of {…} defines the root object. Inside are defined nested objects such as glossary, GlossDiv, GlossList, GlossEntry, etc. The objects also include name-value pairs. If you look at the GlossEntry object, the member variables are ID, SortAs, GlossTerm, etc. In our example, these are all string values, but these could have been any of the basic data types such as integer, real, etc.

Now observe the object GlossDef, you will see that it contains a JSON array which is denoted by [...]. JSON can contain array of the normal data types and also objects. In our case we have an array of strings, with the value GML, XML.

JSON and Android


You can use either the JSONObject found in the org.json library or the JSONReader found in android.util. In the following tutorial we will be learning how to use JSONObject to parse our JSON data. This is because, the JSONObject has been a part of android since API level 1 while JSONReader has been added more recently, since API Level 11. So if you plan to support your application for older Android versions, be careful with your choice of implementation.

JSON Parser


Here is the code for the JSON Parser which parses the sample data provided above and displays it in a TextView.

Explanation and suggestions


Create the root object as a JSONObject. It’s constructor takes a string as input. We call the getType(String name) where the Type could be either a JSONObject, a JSONArray or a basic data type. These methods return data if the value is of Type or if the value can be converted to the requested Type.

There is another method of the form optType(String name, Type optional), where the variable is optional. The user can specify a default value which is returned if the field is missing.

In our example, we use the getString() extensively as most of the fields are string fields. In the GlossDef object, one of the fields [GlossSeeAlso] is of the array type. We have used the getJSONArray() method to obtain it.

The length() method returns the size of the array in case of JSONArray and the number of member variables in case of the JSONObject.

The Final review


We learnt,

  • basics of JSON
  • how to write a JSON parser using the JSONObject.

You can find the code here.

WITER – AsyncTask… What? Why? How?

The Problem


In the previous post, we learnt how to receive data from a server. One of the requirements was to complete the long running task of receiving the data in a thread other than the UI thread. This was to avoid the Application Not Responding (ANR) problem. We chose AsyncTask to do this. Here we explain the what, why and how of the AsyncTask.

For more info on the application that we are building, click here.

The What and the Why?


As per the general working of an android application, everything happens in a single process in a single thread (unless otherwise specified). The main thread is the UI thread and all UI activities are to be done in this. Android suggests that no long running task should be done that could block the UI. If you do, then be sure to meet any android developer’s arch nemesis, the ANR! To avoid such scenarios, Android suggests using worker threads which take care of the heavy tasks and then use the main UI thread to update the UI.

This can be done using normal threads but Android was kind enough to provide a special way to perform such asynchronous tasks. Given the fact that multi-threading is an integral part of the design, AsyncTask definitely makes a developer’s life lot simpler.

The Android Developer’s site has to say the following about AsyncTask which is exactly what it is,

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

The How


Let us now get on to the more interesting part of the AsyncTask. But before that lets us just list down the main methods that you must know to use it in an optimum way.

  • AsyncTask: This is the class declaration and must be subclassed in order to be used. The 3 generic types must be specified at the time of subclassing. They are,
    1. Params: This is the type that is sent when execute() is called. They are the parameters that would be required by the background execution. The parameters are always sent as an array.
    2. Progress: You can update the UI at regular intervals while the background execution is carried on. This type provides the unit in which the progress is to be reported. Eg int for a progressbar, String for progress messages.
    3. Result: This is used to specify the result type. Could be a computed value, a boolean to notify success.
  • Following are the 5 methods that have to be implemented to get the AsyncTask functioning well.

  • onPreExecute(): This method is called as soon as we call execute() on the AsyncTask object. The method is called on the UI thread and as a result UI activities like setting up progress bars, initializing views etc can be done here.
  • doInBackground(Params… params): This is where all the stuff happens and is a mandatory method to be implemented to get an AsyncTask up and running. All tasks running here are done in a separate thread. To update the UI with any progress, publishProgress(Progress…) can be used. We can either send string messages as updates or units of whatever progress type we have defined.
  • onProgressUpdate(Progress… values): This is another method which runs on the UI thread and updates the UI with the progress of the task. The data sent by publishProgress(Progress…) is received here and utilized for updating the UI.
  • onPostExecute(Result result): This is called after the task is completed. The return value of the doInBackground(Params… params) is received here. For example, you could receive a boolean value to denote whether the task was successful or not.
  • onCancelled(Result result): This method is used to handle the UI activities if the action is cancelled midway. The result from doInBackground(Params… params) is received here, so that it can be used to handle the Cancel scenario. This has been introduced in API 11. Prior to this the method onCancelled() is used. It runs on the UI thread after cancel(boolean) is invoked and doInBackground() has finished.

Under the hood


In our previous post, we had written the HttpManager core code inside the AsyncTask. Here is the skeleton code of the AsyncTask. Since our HttpManager doesn’t require progress updates, we have not implemented the onProgressUpdate(Progress… values) method. HttpQuery is the extended AsyncTask() which has a constructor that is used to pass all the parameters that are required in the methods of the HttpQuery.

We override the onPreExecute() to start a progress dialog and also implement the onCancel of the dialog, so that our user can stop updating the latest info if he wishes to do so.

The doInBackground() takes the url that is to be downloaded and on success returns a true. The http related code has been explained in the previous post.

The onPostExecute() gets the result from the method above and based on it displays a message. And then dismisses the dialog.

Final Review


We learnt,

  • How to extend an AsyncTask to perform a long running task in a worker thread and as a result avoid an ANR.
  • The various methods in the Asynctask that can be overridden and what they do.
  • How to add a progress dialog and dismiss it while a long running task is run in the background.

The code provided in the previous post will suffice. Run it and observe the progress dialog. You can also check the LogCat in your Eclipse for the success/fail messages.

WITER – A simple HttpManager with the Apache Http Client

The Problem


We are building an app, [WITER], which gives us the exchange rates and we are using a free open source API available at . The API returns a JSON string containing the current rates. Our first task is to get the information from the web. How do we manage the data downloading?

For more info on WITER, click here.

The Basics


Early on in your Android development, you will realize that, your app will be required to send/receive data from the internet. It could be content from a server, a response to a request you post, or just plain sending information to some site.

There are 2 ways, in which this can be done. You can either use HttpUrlConnection (I’ll deal with this later in another tutorial) or Apache Http Client. The reason I chose Apache Http Client is because it is the more widely used client. It is more powerful, stable and has a lot more features. While I mentioned HttpUrlConnection is because the Android team is actively working on this in improving it. They have claimed here on their site that they no longer work on the Apache Http Client. Nevertheless, it serves our requirement.

For WITER, what we need is a HttpManager. A Manager that would take care of sending and receiving data. It should do it asynchronously because one of the most important things in android development is NEVER DO AN EXTENDED TASK ON THE UI THREAD or be prepared the face the wrath of ANR (Activity Not Responding). So any such data related task must always be done on a separate thread.

In the following section we will see how we can address our requirements and what are the components of the Apache Http Client that will help us achieve this.

The Components


In the current simple form of the HttpManager, we will just require,

  1. HttpClient: This is your basic interface to the Apache client. There are a number of overloaded execute() methods which you can use based upon your requirement.
  2. HttpGet: The http method that you will be using. This is the method we will be using in our case, but you could use any of the others such as HttpPost, HttpPut, HttpHead. [Tip! Use HttpHead to check the meta information of your request response without downloading the whole body of the response.]
  3. HttpResponse: You will receive an object of this class as a response to calling execute() on the HttpClient. The HttpResponse contains a HttpEntity which in turn contains the content of the response. This http entity also gives you some meta information such as length, type and whether it is part of a stream, is chunked or is repeatable.

That is pretty much all that you will need at the moment to get started. I have wrapped the whole thing in an AsyncTask to address our requirement of running it in a separate thread. Do not worry about it for the time being and just concentrate on the Http part. I will explain AsyncTask in the next post.

Under the hood


So let us begin the actual coding. We create a new package called com.utilities.witer.HttpManager. Create a new HttpManager.java file in it. We make our HttpManager a singleton class for ease of access and use.

We create a public class that will be used to make the requests.

Finally, here is the code for the core of the HttpManager – the HttpQuery. For now just look at the code inside the method doInBackground().

So we are basically creating a new HttpGet object in the constructor of the HttpQuery. We set the URI of the request object and use the client to execute the request. The result of the execute() is nothing but your http response. To make sure that we have got a valid response we print the Status Phrase of the response object using mResponse.getStatusLine().getReasonPhrase()

That’s it! 3 lines of code and you have your basic HttpManager ready. Now, to check that our HttpManager works properly, let us call it in the MainActivity. We have added a button in the MainActivity which invokes the HttpManager on click.

Before we can run the code and start receiving data, there is one final thing we must do. In your Android Manifest file, add the permission to access the internet

Final Review


Once you run the program and click on the button, you’ll observe the output in your LogCat. At the end of this tutorial, you have learnt how to,

  • Create a HttpManager and pass a request to it.

Here is the code for the HttpManager.

Android Tutorial – What Is The Exchange Rate [WITER]?

The Plan


It’s always fun to have something concrete at the end of a learning exercise. Its like a bonus. So I thought that the best way to explain a few important basic concepts which any android developer would require, was to make an application covering the topics. At the end of it, you would have learnt the concepts and would also have a working application :) So here goes…

Topics to be covered


  • Data access over http
  • AsyncTask
  • JSON Parsing

We will also go through ListView, ViewHolders and Application Context again. Just click on the links to go through tutorials covered previously.

The Project – WhatIsTheExchangeRate(WITER)


Its a currency converter based upon the current Forex rates. We get the Forex Rates from a free open source API available at . The information provided by the API is updated every hour and more details about it can be views at the link mentioned.

The user will be able to set his default currency from the settings page. Once set, all other currencies will be shown in terms of his set currency.

Plan of Action


Let us divide the project into chunks and then tackle one per post.

  1. A simple HttpManager with the Apache Http Client
  2. AsyncTask… What? Why? How?
  3. JSON parser in a jiffy
  4. Options Menu in Android
  5. ViewHolder! Make my ListView pretty

Our aim will be to have a running piece of code illustrating the functioning of the topic covered in each post, so that the code at the end of the post will be working code.

Let us begin by creating a new project called WhatIsTheExchangeRate, a package called com.utilities.witer and name your first activity as MainActivity.

Application Context for all non GUI context requirement

What’s the problem?


I want to make this really cool app with data stored in databases, personal preferences saved for the user, cached images for quick loading and I have realized that I need a reference to the Context to access application specific resources and I have ended up passing my Activity to every class I have designed. Its ugly and potentially dangerous. What do I do?

The boring basics


Context acts as an interface to the global information about the application envirnoment. It is mainly used to load and access resources related to an application. For example, you would require the context to call methods to access the application related directories, application information, start/stop a service, launch an activity, etc. There are typically 2 types of contexts in an android application, Activity and Application, which are nothing but 2 classes that have been derived from the Context class and hence lets you accomplish all that is possible by Context. Mostly, an Activity instance is passed to functions that need access to the context. First let us decide on which context to pass in different circumstances before we figure out how to pass it effectively.

The Application Context is valid as long as the application is alive while the Activity Context is very specific to the Activity and should not be used outside its scope. The reason is that if you pass an Activity Context to a function that lives longer than the Activity, the garbage collector fails to collect it when the Activity is destroyed. In such circumstances, it is always recommended to pass the Application Context. But make sure that you do not pass the Application Context to a function which deals with UI, as it will cause runtime exceptions. Anything that deals with the GUI requires an Activity Context and will not work if you pass it an Application Context. So make sure that the function does not go out of the Activity’s scope.

The solution


So, now that we have the basics in place, lets tackle the problem. From the above discussion and the requirement, we have,

  1. In any non-GUI related context usage, we should always use the application context.
  2. We need a static class that can be used to get a reference to the application context from anywhere in the program.

This can be very easily achieved by subclassing the Application class and keeping a static method that returns the application context. You could also make it a singleton. The added benefit to subclassing is that it can be used to store the global application state. Here’s how to go about it.

Step 1:

Step 2:

In the AndroidManifest.xml, modify the node by adding the parameter android:name=”yourAppContextName”. In our case, it would be android:name=”CustomAppContext”.

And that is how its done! You can now call the CustomAppContext from anywhere in your code and get the Application Context. No need to pass it to all your various functions requiring it.

Final Review


A quick wrap up of what you have learnt in the tutorial

  • How to subclass an Application class and use it to get the Application Context instance anywhere in the application.
  • Never pass the Activity Context to a function that outlives the Activity. It will lead to memory leaks.
  • Never pass an Application Context to any class or function that deals with the GUI as it will produce runtime exceptions