Thursday, May 31, 2012

Custom fonts for Webview And Textviewv in android?


In Android, the three default font options are monospace, sans serif and serif. You do have some flexibility with adding effects to the default fonts, but without custom fonts, you are pretty limited in how text in your Android appears to your users. Luckily, it’s fairly straightforward to set a custom font. You can find plenty of free custom fonts at sites likedafont.com – just download the .ttf file for the font of your choice, and add it to the assets/fonts directory of your codebase (create the directory if it doesn’t exist already).
Custom Fonts in Views
If, for example, you’d like to set the font for a TextView with id=name, it’s as simple as adding the following to your code:

TextView name = (TextView) findViewById(R.id.name);
Typeface  typeface = Typeface.createFromAsset(getContext().getAssets()"fonts/customFont.ttf");
name.setTypeface(typeface)
;


That’s fine when you have just one or two TextViews with custom fonts, but it gets to be a pain when you want customized fonts on all your TextViews. That’s a lot of boilerplate code to have in your activities! It would be convenient to be able to specify the font name in xml. To do this, you can extend TextView:

public class CustomTextView extends TextView {
private static final DEFAULT_FONT="defaultFont.ttf";

  public CustomTextView(Context context) {
    this(context, null);
  }

  public CustomTextView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView, 0, 0);
    String fontName = arr.getString(R.styleable.CustomTextView_fontName);
    // Sets to a default font if none is specified in xml
    if (fontName == null) {
      fontName = DEFAULT_FONT;
    }
    setFont(fontName);
  }

  private void setFont(String fontName) {
    Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/" + fontName);
    setTypeface(typeface);
  }
}


In your attrs.xml (in res/values/, create the xml file if it doesn’t exist already), add an attribute for CustomTextView as follows:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomTextView">
<attr name="fontName" format="string"/>
</declare-styleable>
</resources>


Now you can add a custom font to a TextView in xml, without any additional code to your activities:

<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:example="http://schemas.android.com/apk/res/com.example.customfonts"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
<com.example.customfonts.CustomTextView
       example:fontName="customFont2.ttf"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content" />
</LinearLayout>


That’s it! Now you can easily set custom fonts for views in xml.
Custom Fonts in WebViews
For webviews, you still want to copy the .ttf file into your assets/fonts directory, and then you can create new font-faces in your css and use them by setting font-family:

<style type="text/css"> 
    @font-face { 
        font-family:"customFont1"; 
        src:url('file:///android_asset/fonts/customFont.ttf');
    }
    @font-face { 
        font-family:"PTS55F"; 
        src:url('file:///android_asset/fonts/customFont2.ttf');
    }

    body { font-family:'customFont'; }
    h1 { font-family:'customFont2'; }
</style>


Using custom fonts gives you a lot more control over the visual appearance of your application, but when don’t get carried away — using too many random fonts can make an app seem very disjointed. In general, try to use at most a few fonts that go well together. To get you started, here are 40 free designer fonts.

The Hidden Pitfalls of AsyncTask in android?


When AsyncTask was introduced to Android, it was labeled as “Painless Threading.” Its goal was to make background Threads which could interact with the UI thread easier. It was successful on that count, but it’s not exactly painless – there are a number of cases where AsyncTask is not a silver bullet. It is easy to blindly use AsyncTask without realizing what can go wrong if not handled with care. Below are some of the problems that can arise when using AsyncTask without fully understanding it.
AsyncTask and Rotation
AsyncTask’s primary goal is to make it easy to run a Thread in the background that can later interact with the UI thread. Therefore the most common use case is to have an AsyncTask run a time-consuming operation that updates a portion of the UI when it’s completed (in AsyncTask.onPostExecute()).
This works great… until you rotate the screen. When an app is rotated, the entire Activity is destroyed and recreated. When the Activity is restarted, your AsyncTask’s reference to the Activity is invalid, so onPostExecute() will have no effect on the new Activity. This can be confusing if you are implicitly referencing the current Activity by having AsyncTask as an inner class of the Activity.
The usual solution to this problem is to hold onto a reference to AsyncTask that lasts between configuration changes, which updates the target Activity as it restarts. There are a variety of ways to do this, though they either boil down to using a global holder (such as in the Application object) or passing it through Activity.onRetainNonConfigurationInstance(). For a Fragment-based system, you could use a retained Fragment (viaFragment.setRetainedInstance(true)) to store running AsyncTasks.
AsyncTasks and the Lifecycle
Along the same lines as above, it is a misconception to think that just because the Activity that originally spawned the AsyncTask is dead, the AsyncTask is as well. It will continue running on its merry way even if you exit the entire application. The only way that an AsyncTask finishes early is if it is canceled via AsyncTask.cancel().
This means that you have to manage the cancellation of AsyncTasks yourself; otherwise you run the risk of bogging down your app with unnecessary background tasks, or of leaking memory. When you know you will no longer need an AsyncTask, be sure to cancel it so that it doesn’t cause any headaches later in the execution of your app.
Cancelling AsyncTasks
Suppose you’ve got a search query that runs in an AsyncTask. The user may be able to change the search parameters while the AsyncTask is running, so you call AsyncTask.cancel() and then fire up a new AsyncTask for the next query. This seems to work… until you check the logs and realize that your AsyncTasks all ran till completion, regardless of whether you called cancel() or not! This even happens if you pass mayInterruptIfRunning as true – what’s going on?
The problem is that there’s a misconception about what AsyncTask.cancel() actually does. It does not kill the Thread with no regard for the consequences! All it does is set the AsyncTask to a “cancelled” state. It’s up to you to check whether the AsyncTask has been canceled so that you can halt your operation. As for mayInterruptIfRunning – all it does is send an interrupt() to the running Thread. In the case that your Thread is uninterruptible, then it won’t stop the Thread at all.
There are two simple solutions that cover most situations: Either check AsyncTask.isCancelled() on a regular basis during your long-running operation, or keep your Thread interruptible. Either way, when you call AsyncTask.cancel() these methods should prevent your operation from running longer than necessary.
This advice doesn’t always work, though – what if you’re calling a long-running method that is uninterruptible (such as BitmapFactory.decodeStream())? The only success I’ve had in this situation is to create a situation which causes an Exception to be thrown (in this case, prematurely closing the stream that BitmapFactory was using). This meant that cancel() alone wouldn’t solve the problem – outside intervention was required.
Limitations on Concurrent AsyncTasks
I’m not encouraging people to start hundreds of threads in the background; however, it is worth noting that there are some limitations on the number of AsyncTasks that you can start. The modern AsyncTask is limited to 128 concurrent tasks, with an additional queue of 10 tasks (if supporting Android 1.5, it’s a limit of ten tasks at a time, with a maximum queue of 10 tasks). That means that if you queue up more than 138 tasks before they can complete, your app will crash. Most often I see this problem when people use AsyncTasks to load Bitmaps from the net.
If you are finding yourself running up against these limits, you should start by rethinking your design that calls for so many background threads. Alternatively, you could setup a more intelligent queue for your tasks so that you’re not starting them all at once. If you’re desperate, you can grab a copy of AsyncTask and adjust the pool sizes in the code itself.

Faster Screen Orientation Change with Android gives Error?


Android is a mobile operating system meant to be run on a wide array of devices, with very different hardware configurations. Some devices, like the T-Mobile G1, can change their hardware configuration at runtime. For instance, when you open the keyboard, the screen change from the portrait orientation to the landscape orientation. To make Android applications development easier, the OS automatically handles configuration changes and restart the current activity with the new configuration. This is the default behavior that lets you declare resources like layouts and drawables based on the orientation, screen size, locale, etc. If you are not familiar with the way Android handles resources, I highly suggest you to read the official documentation on resources.
While this behavior is really powerful, since your application adapts automatically to the device’s configuration at runtime, it is sometimes confusing for new Android developers who wonder why their activity is destroyed and recreated. Facing this “issue,” some developers choose to handle configuration changes themselves which is, in my opinion, a short-term solution that will complicate their life when other devices come out or when the application becomes more complex. The automatic resource handling is a very efficient and easy way to adapt your application’s user interface to various devices and devices configurations. It sometimes comes at a price though.
When your application displays a lot of data, or data that is expensive to fetch, the automatic destruction/creation of the activities can be lead to a painful user experience. Take the example of Photostream, a simple Flickr browsing application I wrote for the release of Android 1.0. After you launch the application and choose a Flickr account, the application downloads a set of 6 photos (on a T-Mobile G1) from the Flickr servers and displays them on screen. To improve the user experience, I also use slightly different layouts and drawables in portrait and landscape, and this is what the result looks like:

Photostream lets Android take care of the configuration change when the screen is rotated. However, can you imagine how painful it would be for the user to see all the images being downloaded again? The obvious solution to this problem is to temporarily cache the images. They could be cached on the SD card (if there’s one), in the Application object, in a static field, etc. None of these techniques is adapted to the current situation: why should we bother caching the images when the screen is not rotated? Fortunately for us, Android offers a great API exactly for that purpose.
The Activity class has a special method called onRetainNonConfigurationInstance(). This method can be used to pass an arbitrary object your future self and Android is smart enough to call this method only when needed. In the case of Photostream, I used this method to pass the downloaded images to the future activity on orientation change. The implementation can be summarized like so:

@Override
public Object onRetainNonConfigurationInstance() {
    final LoadedPhoto[] list = new LoadedPhoto[numberOfPhotos];
    keepPhotos(list);
    return list;
}

In the new activity, in onCreate(), all you have to do to get your object back is to call getLastNonConfigurationInstance(). In Photostream, this method is invokedand if the returned value is not null, the grid is loaded with the list of photos from the previous activity:

private void loadPhotos() {
    final Object data = getLastNonConfigurationInstance();
    // The activity is starting for the first time, load the photos from Flickr
    if (data == null) {
        mTask = new GetPhotoListTask().execute(mCurrentPage);
    } else {
       // The activity was destroyed/created automatically, populate the grid
        // of photos with the images loaded by the previous activity
        final LoadedPhoto[] photos = (LoadedPhoto[]) data;
        for (LoadedPhoto photo : photos) {
           addPhoto(photo);
        }
    }
}

Be very careful with the object you pass through onRetainNonConfigurationChange() though. If the object you pass is for some reason tied to the Activity/Context, you will leak all the views and resources of the activity. This means you should never pass a View, a Drawable, an Adapter, etc. Photostream for instance extracts the bitmaps from the drawables and pass the bitmaps only, not the drawables. Finally, remember that onRetainNonConfigurationChange()should be used only to retain data that is expensive to load. Otherwise, keep it simple and let Android do everything.

How to Solve Initial Compilation Issues with Android?

Two weeks ago I helped with a beginner's Android Workshop at Mobile March.  A lot of the people had problems getting their development environment up and running - but for reasons that weren't really any fault of their own, or were easily overlooked.  Typically once you've got all the gears in place building is simple, but I'd forgotten how surprisingly difficult it can be to get a project up and running in Eclipse initially.

Here's a few common problems I saw around the classroom:

Installing the Android SDK (the tools for Android) but not the ADT plugin (how Eclipse interfaces with the SDK), or vice versa.  Make sure both are installed.

- Not installing any Android platforms (or not installing the correct one for the app you're trying to build).  The SDK is just a starter package - from there, you need to run the Android SDK Manager and add SDK components.  There's an SDK platform for each version of Android; I recommend just installing the whole lot (it takes time to download, but makes everything else easy).

If you get compilation errors upon importing a project, do a full clean and rebuild.  Clean is found in Project --> Clean.  This can sometimes clear up import issues.

Compilation issues with @Override.  If you're getting compilation error on @Override, that's because your JDK compliance level is set incorrectly.  You either need to go into Eclipse --> Preferences --> Java --> Compiler and set the compliance level to 1.6+, or you need to go into the individual project and change that setting (right-click the project --> Properties --> Java Compiler --> Compiler compliance level).


Using emulators that are not compatible with your sample app.  If your app targets 2.3, you must have a 2.3 (or higher) emulator.  If your app uses Google Maps, your emulator must be a "Google APIs" emulator (and also conform to the previous version requirement as well).


Did you try Android briefly more than a year ago and now it refuses to work?  Chances are the problem is an invalid debug.keystore.  When you build in Eclipse, it creates your APK using an automatically generated debug keystore.  Older versions of Android had these set to expire a year after creation, so if you dabbled in Android before it may have expired.  You can find the path to your debug.keystore by going into Preferences --> Android --> Build.  You can safely delete your old debug.keystore and the Android build process will automatically create a new, valid one for you.

If none of the above helps, I found the most useful debugging tool for build errors was to turn on verbose output.  You can turn that on in Preferences --> Android --> Build --> Build Output, then check the Console for any salient error messages.

Good luck getting your first Android app building!

TextWatchers and onRestoreInstanceState() creating problem in android?

There's a small timing issue I'd like to mention because it's bitten me a few times now.

When you want to observe changes to an EditText, you add a TextWatcher to it (via TextView. addTextChangedListener()). There are a lot of uses for TextWatchers, like implementing your own autocomplete or filters based on a dynamic EditText. The only thing you have to be careful of is whether the text was changed by the user or the code - the listener fires either way.

What's worth knowing about an EditText is that it will save and restore the state of the text inside of it within your Activity. That means that when you rotate the screen, the EditText will restore the text that was inside of it. And most importantly, the automated restoring of the text on rotation causes the TextWatcher's methods to fire. Like I said - the TextWatcher doesn't discern between whether the user changed the EditText or the system did.

The solution is simple - just don't add the TextWatcher until after the EditText's content has been restored. It restores itself in Activity.onRestoreInstanceState(), which makes Activity.onResume() the preferred time to add TextWatchers to any EditTexts.

Using Subquery Columns on Android with SQLite?

Take a look at this (contrived) query, as might be passed to SQLiteDatabase.rawQuery():
SELECT *
FROM t1 A, (SELECT T2.id FROM t2 T2) B
WHERE A.id = B.id

On Android 2.1 and below, this query will cause your app to crash. You'll get an error like this:

Caused by: android.database.sqlite.SQLiteException: no such column: B.id: , while compiling: SELECT * FROM t1 A, (SELECT T2.id FROM t2 T2) B WHERE A.id = B.id
    at android.database.sqlite.SQLiteProgram.native_compile(Native Method)
    at android.database.sqlite.SQLiteProgram.compile(SQLiteProgram.java:110)
    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
    at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:49)
    at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:49)
    at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1220)
    at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1193)
    at com.mycompany.myapp.MyActivity.onCreate(QuickTestActivity.java:22)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
    ... 11 more

It turns out that SQLite throws this error if two conditions are met:

  1. You use a subquery (in this case, the select subquery from table t2).
  2. Your subquery has a table alias (in this case, referencing table t2 as "T2").

The solution is simple: alias the selected field names. This query will work:

SELECT *
FROM t1 A, (SELECT T2.id AS id FROM t2 T2) B
WHERE A.id = B.id

I'm hardly an expert on SQL or SQLite, so I don't know whether this is a bug or just me running into undefined behavior. I ran into this problem when doing JOINs on multiple tables, so as contrived as my example is, it can happen. Regardless, it is easy to work around.

How to Detect the Keystore Signature through code in Android?


Here's a problem I'm sure many of us have faced: you've got code that runs one way when you're developing and another way when you're releasing. A few examples I've run into:

- Logging during development, but disabled for release.
- Targeting development vs. production servers.
-
 MapView requires an API key tied to the signing key.

Before, I just setup static parameters in code that I'd have to remember to change before making a release build. It's a pain and error prone.

I've just determined a much better (and more automatic) way - detecting the
 signing keystore in code. Through use of the PackageManager you can actually determine the Signature of the app that's currently running.

First, you need to get the Signature of your release keystore. Put this code into your application temporarily, then sign it with your release keystore and run it:
PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
Log.i("test", pi.signatures[0].toCharsString());

Take the output from logcat and put it into this method:
private static final Signature SIG_RELEASE = new Signature("<YOUR SIGNATURE HERE>");

public static boolean isRelease(Context context) {
 try {
  PackageManager pm = context.getPackageManager();
  PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
  for (Signature sig : pi.signatures) {
   if (sig.equals(SIG_RELEASE)) {
    return true;
   }
  }
 }
 catch (Exception e) {
  Log.w("Exception thrown when detecting if app is signed by a release keystore.", e);

  // Return true if we can't figure it out, just to play it safe
  return true;
 }

 return false;
}

Now you can always call isRelease() and check whether your app was signed by your release keystore. No more having to edit files to create a release version of your app - just sign it with the correct keystore and you're ready to go!

Tuesday, May 29, 2012

What is Template Design Patter in Java?


An abstract class defines various methods and has one non-overridden method which calls the various methods.
Wikipedia Says:
A
 template method defines the program skeleton of an aligorithm.The aligorithm itself is made abstract,and the subclasses override the abstract methods to provide concrete behavior.First a class is created that provides the basic steps of an aligorithm design.These steps are implemented using abstract methods.Later on subclasses change the abstract methods to implement real actions.Thus the general aligorithm is saved in one place but the concrete steps may be changed by the subclasses.
Non-Abstract Methods are completly controlled by the Template Method.In contrast the
 template method need not be changed and is not an abstract operation and thus may guarentee required steps before and after the abstract operations.Thus the template method is invoked and as a consequence the non-abstract methods and abstract methods are called in the correct sequence.
Intent: Define the skeleton of an aligorithm in an operation,deferring some steps to subclasses.Template methods lets subclasses redefine certain steps of an aligorithm without changing the aligorithm structure .[DesignPatterns, p. 325]
Motivation:
Sometimes we want to specify the order of operations that a method uses,but allow subclasses to provide their own implementation of some of these operations.When ever we see two methods in subclasses,it makes sense to bring the methods together into a superclass method.
Applicability:
Use the Template method pattern:
·         To implement the invariant parts of an aligorithm once and leave it up to subclasses to implement the behavior that can vary.
·         To localize common behavior among subclasses and place it in a common class(in this case a superclass) to avoid code duplication.This is a classic example of “code refactoring”.
·         To control how subclasses extend superclass operations.You can define a template method that calls “hook” operations at specific points,there by permitting extensions only at that point.
THE TEMPLATE METHOD IS A FUNDAMENTAL TECHNIQUE FOR CODE REUSE
Problem:
Two different component have significant similarities,but demonstrate no reuse of common interface or implementation.If a change common to both components becomes necessary,duplicate effort must be expended.
Discussion:
The component designer decides which steps of an aligorithm are invariant(or standard) and which are variant(or customizable).The invariant steps are implemented in an abstract base class,while the variant steps are either given a default implementation or no implementation at all.The “variant” steps represent “hooks”,or “placeholders” that can or must be supplied by the component’s client in a concrete derived class.
The component designer mandates the required steps of an aligorithm,and the ordering of the steps,but allow the component client to extend or replace some number of steps.
Template methods
 are prominently used in frameworks.Each framework implements the invariant pieces of domain’s architecture,and defines “placeholders” for all necessary or interesting client customization options.The inverted control structure has been affectionately labelled “the hollywood principle” – Don’t call us we will call you.

Usage:
The template method is used to:
·         Let subclasses implement behavior that can vary.
·         Avoid duplication in the code.We look for general code in the aligorithm and implement variants in the subclasses.
·         Control at what point(s) subclassing is allowed.
Implementation Issues:
·         Operations which must be overridden by subclasses should be made abstract.
·         If the template method itself should not be overidden by subclasses it should be made final.
·         To allow a subclass to insert code at a specific spot in the operation of the aligorithm,insert “hook” operations into the template method.These hook operations may do nothing by default.
·         Try to minimize the number of operations that a subclass must override.
·         In a template method parent class calls the operations of a subclass and not the other way round.
Example:
The template method defines a skeleton of an aligorithm in an operation and defers some steps to subclasses.Home Builders use the template method when developing a new subdivision.A typical subdivision consits of a limited number of floor plans with diff variations available for each.Within a floor plan, the foundation, framing, plumbing, and wiring will be identical for each house. Variation is introduced in the later stages of construction to produce a wider variety of models. [Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54]
Template method pattern could be refactored using an interface that explicitly signals the methods requested to subclasses and also the state needed by them from the abstract class.
Rules of Thumb:
Strategy is like Template Method except in its granularity.[Coplien, C++ Report, Mar 96, p88]
Template method uses inheritance to vary part of an aligorithm.Strategy uses delegation to vary the entire aligorithm. [GOF, p330]
Also Alex has a good explanation of why he hates Template Pattern.Even i do agree to some extent.
Below example gives an implementation of Template Design Pattern.
package patterns;

abstract class TitleInfo {
 private String titleName;

 // The Template Method.
 // Calls the concrete class methods,is not overridden

 public final String processTitleInfo() {
  StringBuffer titleInfo=new StringBuffer();
  titleInfo.append(this.getTitleBlurb());
  titleInfo.append(this.getDvdEncodingRegionInfo());
  return titleInfo.toString();
 }

 public final void setTitleName(String titleNameIn) {
  this.titleName=titleNameIn;
 }

 public final String getTitleName() {
  return this.titleName;
 }

 public abstract String getTitleBlurb();

 public String getDvdEncodingRegionInfo() {
  return " ";
 }

}

class DvdTitleInfo extends TitleInfo {
 String star;
 char encodingRegion;

 public DvdTitleInfo(String titleName,String star,char encodingRegion) {
  this.setTitleName(titleName);
  this.setStar(star);
  this.setEncodingRegion(encodingRegion);
 }

 public char getEncodingRegion() {
  return encodingRegion;
 }

 public void setEncodingRegion(char encodingRegion) {
  this.encodingRegion = encodingRegion;
 }

 public String getStar() {
  return star;
 }

 public void setStar(String star) {
  this.star = star;
 }

 public String getTitleBlurb() {
  return ("DVD: " + this.getTitleName() + ", starring " + this.getStar());
 }

 public String getDvdEncodingRegionInfo() {
        return (", encoding region: " + this.getEncodingRegion());
    }
}

class BookTitleInfo extends TitleInfo {
 private String author;

 public BookTitleInfo(String titleName,String author) {
  this.setAuthor(author);
  this.setTitleName(titleName);
 }

 public String getAuthor() {
  return author;
 }

 public void setAuthor(String author) {
  this.author = author;
 }

 public String getTitleBlurb() {
  return ("Book: " + this.getTitleName() + ", Author: " + this.getAuthor());
 }
}

public class TemplatePatternDemo {

 public static void main(String[] args) {
  TitleInfo bladeRunner=new DvdTitleInfo("Blade Runner","Harrison Ford",'1');
  TitleInfo electricSheep=new BookTitleInfo("Do Androids Dream of Electric Sheep?","Philip");

  System.out.println(" ");
  System.out.println("Testing bladeRunner" + bladeRunner.processTitleInfo());
  System.out.println("Testing electricSheep" + electricSheep.processTitleInfo());
 }
}