Working with Camera on Android SDK

I wanted to write a quick custom camera android app.
Before we start to write your custom camera app, here are the things we have to aware of.
1. Detect and access Camera
2. Create a preview class
3. Build a preview layout
4. Setup Listeners for Capture
5. Capture and Save files

Lets Start…
Detecting and access Camera
In the Android project, we will have to add Camera permission and feature.
Add following lines in the Manifest.xml

 <uses-feature android:name="" />
 <uses-permission android:name="android.permission.CAMERA" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

This will get the Camera permission for the application.
(we are asking for permission to write to external storage so we can save image there)
Devices running android 2.3 or higher, we can access specific camera as devices could have more than 1 camera. In this example we will use the back facing camera.

Create a preview class
We create a preview class that simply extends “SurfaceView” which will allow us to show what the ‘camera’ sees.
Also, in order to capture the callback events for creating and destroying the view, which are needed for assigning the camera preview input, we will implement “SurfaceHolder.Callback” interface.

Here is the code for preview class

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

	private SurfaceHolder mSurfaceHolder;
	private Camera mCamera;

	//Constructor that obtains context and camera
	public CameraPreview(Context context, Camera camera) {
		this.mCamera = camera;
		this.mSurfaceHolder = this.getHolder();
		this.mSurfaceHolder.addCallback(this); // we get notified when underlying surface is created and destroyed
		this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); //this is a deprecated method, is not requierd after 3.0

	public void surfaceCreated(SurfaceHolder surfaceHolder) {
		try {
        } catch (IOException e) {
          // left blank for now

	public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

	public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
			int width, int height) {
		// start preview with new settings
		try {
		} catch (Exception e) {
			// intentionally left blank for a test

Build a preview layout
Let’s create a Layout where the preview is displayed and the user can click on a button to take a picture.
Change the content of the “main.xml” under the layout directory in your android app.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""


Now, lets wire up the Camera Activity

public class DVCameraActivity extends Activity {
	private Camera mCamera;
	private CameraPreview mCameraPreview;
	/** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        mCamera = getCameraInstance();
        mCameraPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = (FrameLayout) findViewById(id.camera_preview);

     * Helper method to access the camera returns null if
     * it cannot get the camera or does not exist
     * @return
	private Camera getCameraInstance() {
		Camera camera = null;

		try {
			camera =;
		} catch (Exception e) {
			// cannot get camera or does not exist
		return camera;

At this point if you run your application, you will see what the camera sees.
To make something meaningful, lets add listener to capture the image.

Setup Listeners for Capture
In order for us to take the picture, we will have to setup the listeners.
Lets make a inner class inside the Activity we created above,

PictureCallback mPicture = new PictureCallback() {

		public void onPictureTaken(byte[] data, Camera camera) {
			 File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
		        if (pictureFile == null){

		        try {
		            FileOutputStream fos = new FileOutputStream(pictureFile);
		        } catch (FileNotFoundException e) {

		        } catch (IOException e) {

It is using a helper method called, “getOutputMediaFile”, here is the code for that

/** Create a File for saving the image */
	private static File getOutputMediaFile(){

	    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
	              Environment.DIRECTORY_PICTURES), "MyCameraApp");

	    if (! mediaStorageDir.exists()){
	        if (! mediaStorageDir.mkdirs()){
	            Log.d("MyCameraApp", "failed to create directory");
	            return null;

	    // Create a media file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
	    File mediaFile;
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
	        "IMG_"+ timeStamp + ".jpg");

	    return mediaFile;

Let’s wire up the listener onCreate method

 //Adding listener
        Button captureButton = (Button) findViewById(id.button_capture);
        		new View.OnClickListener() {
					public void onClick(View v) {
						mCamera.takePicture(null, null, mPicture);

After you have all this wired, the application i ready to fire up some pictures.



Installing Nepali/Devnagari Font in Android

Update: If you do not want to mess with ADB Follow the steps from my new post about Yet another way to Install Nepali/Devnagari font on Android devices.

One of the issues with Android is that it doesn’t come with Nepali / Devanagari font by default. When I visit websites with Nepali font or have posting on Facebook with Nepali text, it shows up as boxes. Similar to image below.

It started to be more annoying as I would get emails in Nepali font, and I would have to check it on a computer.
So after tinkering around, I am happy to report that I have a solution.
This is how I solved it:
Download the Font (DroidSansFallback.ttf) on your SDCard:

Using ADB (You may be able to use some “Explorer app” with root access. adb is simple if you have Android SDK installed)

go to the device console:

$ ./adb shell

Mount your phone drive so you can have write access to system folder

# mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system

Now, Simply copy over the font from your sdcard to “/system/fonts”.
(font might be already existing on the device, you can just overwrite it.)

# cp /mnt/sdcard/DroidSansFallback.ttf /system/fonts

(Note: DroidSansFallback.ttf is stored on the root of the sdcard.)
Thats it, now reboot your device and your device should render Nepali font with no issues ūüôā

Hope this helps!

Building a Native (kind of) Android App using Grails, HTML 5, CSS, Javescript hosted on CloudFoundry

Been very busy with personal life lately and haven’t had time to do much of interesting stuff specifically on CloudFoundry, Grails and Android.
Here is my attempt to build an android application entirely based on HTML 5, CSS and JS. Ever since I found out that LinkedIn built their Mobile app based on those technologies instead of pure native application. I have been very interested in trying it out myself.
I truly am a believer in CloudFoundry! I think it is going to change how “Cloud” service is provided (PaaS). (Wanted to blog about CloudFoundry Micro but my machine doesn’t Support VT ūüė¶ so may be will get to blog about it sometime later…)

Let’s Jump on to our today’s topic.
Here is my vision:
1. Build a Grails application that is hosted on cloudfoundry. This will serve as a mobile website. I will be using jQuery Mobile.

2. Build a Native looking app using PhoneGap that will interface to the grails web application hosted on cloudfoundry.

About the application:

We will build an android application that will give events that are going on around you given your location. We will be using YQL to get the data. You can learn more about YQL at

Since I want it to be a good size blog entry and not to long, This will be part I of the application.
By the end of this blog I should have.
1. Grails App optimized for mobile hosted on Cloudfoundry
2. Android App based on PhoneGap that will serve as an interface to the Grails App built above.

Let’s Start with the first part:

Building Grails App and hosting it on CFoundry:

I am going to build it from the ground up. I may skip few things, but, if you just want to know how this is done, you can read my old blog post about building a grails app on Cfoundry here.

Creating Grails app and installing the CFoundry plugin:

  $ grails create-app FindEventsGA
  $ grails install-plugin cloud-foundry

(Note: Refer to the link above to set up your Cloudfoundry account in Config.groovy)

Setting up jQuery Mobile Test page:
If you followed me till here you should have a standard grails app all ready to go.
Now, Lets wire up the jQuery Mobile. At the time of this writing, jQuery Mobile Beta 3 was the latest.
Now Navigate to your “index.gsp” in your “views” folder and replace the current content with the following content.


<!DOCTYPE html> 
<title>Grails Mobile App on CloudFoundry</title> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<link rel="stylesheet" href="" />
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<div data-role="page" id="dashboard">
	<div data-role="header">
	</div><!-- /header -->

	<div data-role="content">	
		<p>Hello From Grails Mobile App!</p>	
	</div><!-- /content -->
</div><!-- /page -->

Above HTML 5, will replace the standard Grails homepage.
In the Page above, it simply imports jQuery Mobile JS and CSS.
You can read more about them at jQuery Mobile page

Now we are ready to publish the app.

Lets run the following command from the grails project directory and verify that it renders the page correctly.
(Note: If you are using Eclipse with Grails plugin or STS, you can simply press “Ctrl+Alt+Shit+G” –> This will give you grails command prompt where you can simply type “prod cf-push”)

$ grails prod cf-push

I set up my application to be hosted under “;
After the app has been published, We can get to it through a browser.
See an screen Shot below.

Since I have pushed the app up in the cloudfoundry “cloud”, I can navigate to it from my mobile browser.
Here is how it looks on the device.

We are half way done! – Building a native application
Now the web app is ready, Let’s set up the android application.

Create a new android project on Eclipse or any other IDE of your choice. ( has tutorials if you are new to Android development.)

After you have a Android Project ready. We will go to PhoneGap and download their Jars.

Go to PhoneGap website and download their android tools.

Unzip the file and place following artifacts.

1. Get the Android “phonegap-1.0.0.jar” (or whatever version you get) from and “Android” directory in the zip and place it in your Project under “libs” folder. (Create the “libs” directory under your android project)

2. In your android project, create “www” folder under “assets” folder (assets folder should already be in your android project). Copy the “phonegap-1.0.0.js” found in the Android folder in the zip file into this www directory.

3. Copy the “xml” folder found in the Android folder inside the zip file into “res” folder in your android application.

Your Project should look similar to one below:

As we added the jar, let’s add it to the build path.
To do this, simply right click on the project and click on “Properties”.
Navigate to “Java Build Path”>”Libraries”. Click on “Add JARs…” and point to the phonegap jar.

Now, navigate to your Main Activity on your android Project and make following changes.

1. Extend the activity to “DroidGap” instead of “Activity”

2. add URL to your grails application.


Your class may look similar to the following:

import android.os.Bundle;

import com.phonegap.DroidGap;

public class FindEventsGADroidActivity extends DroidGap {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

Now let’s change the AndroidManifest.xml and we are ready for the show time.

Add following xml before the <application tag

		android:anyDensity="true" />

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

Add android:configChanges="orientation|keyboardHidden" to the activity tag in AndroidManifest. (view image below)

Add a second activity below under you application tag in AndroidManifest. (view image below)

<activity android:name="com.phonegap.DroidGap" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden"> 
     <intent-filter> </intent-filter>

Your Manifest should look something like below:

Learn more about PhoneGap at

We are done!

Show Time
Run your application and you should see the Grails app that will apear like a native application on your device.

See below for a screen shot of my application.

We have accomplished our goal for this post and are at a good stopping point.
We now have a grails app thats running on cloudfoundry appear as a native app on Android!

In the next post I will be working on gestures etc on grails app and will use YQL.
Most interestingly use device gps etc to find location. We will have to make some significant changes to the project. Hope you enjoyed this post.

Integrating AdMob in your Android App and make money

As an android developer, I write android apps and publish them on the market mostly for free as I try to build a reputation :). But, wouldn’t it be great if I could offer my app for free at the same time make some $$ through “Advertisement”? In this post I will go through integrating AdMob in an android application and start making some money (at least few cents ;)).

If you want to learn more about AdMob, please visit their website

Let’s get started:

Step 1: Registering with AdMob
First of all you need to register yourself with AdMob. You can do this by simply clicking on “Register” Link when you visit “”.

You can find more info about registration in

Step 2: Setting up AdMob with your App

Once you are registred, login to the site and follow link to You can get here by clicking on “Android” Icon on the homepage. (At the time of this writing AdMob website has an icon in the center of the page that features, iPhone, Android etc, I assume that link above should still work.)

i. Click on “Get Started” and then click on “Sites & Apps”. You can follow the link

ii. Click on “Add Site/App” button, this should take you to a setup wizard. In this example we will be working on an android app. Click on “Android App”

iii. Provide the Details. Put your app name under “App Name” (In this example I used “Demo”), As this is a new app and we haven’t published the app yet, you can put your website in the “Android Package URL”. (This is a required filed, so you have have something here). Select a category and add description and click “Continue”.

iv. Thats it you have successfully set up your “App” on AdMob. (You will see a page from where you should be able to download the admob library, if you do this now, you can skip Step 3 below.)

Step 3: Getting the AdMob library jar

If you did not download the jar that you saw at the end of Step 2. You can still get there by navigating to¬†¬†You should see the app you registered in Step 2. ¬†If you hover over the app name, you should see “Manage Settings”, Click on that. This should land you to a page from where you can get the library by clicking on “Get Publisher Code”.

Step 4: Setting up an Android App

¬†Let’s create an Android a Demo app. You can do this by going into Eclipse or any IDE with Android SDK and creating a new project.

Step 5: Adding the Library:

Once you have the android project set up create a directory called “libs”, and add the jar file you downloaded in step 3.

Now, go to the project properties by right clicking on the project name and clicking on “Properties”. ¬†Go to “Java Build Path”, then on the right side, click on “Libraries” tab.

To add the jar, click on “Add JARs…” button and locate the Jar file in the libs folder in your project.

Step 6: Setting up a view

Since you added the lib and if you do not see any project problems you are all set. Now this should allow us to use a “AdView” in your android app. This is the view where AdMob will place a HTML5 advertisement.

There are two ways we can add this view, 1. in the Activity java code or 2. in the Layout XML. For Simplicity, lets do the XML one.

If you have the project set up lets go to the main layout of the app found in “res>layout” directory in your project. Locate “main.xml”.

In the XML, Lets Copy Paste the following XML in your layout.

< android:id="@+id/adView"
                         ads:adUnitId="YOUR_PUBLISHER_ID HERE"

Replace “YOUR_PUBLISHER_ID HERE”, with id you got while in Step 3.

Also, Include following namespace code int he Layout tag.


So your final code should look something like this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    < android:id="@+id/adView"

Step 7: Setting the Manifest
AdMob requires internet and network access, so it can pull down the ad to display on your app. So, Lets update the AndroidManifest.xml.
Edit the AndroidManifest.xml file found in your project. Add Following Activity right below the current activity.

    <activity android:name=""

And Now, add following permissions

<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Your Manifest should look something like:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".CouponManager"
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

 	<activity android:name=""


    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


Step 8: Done!
That’s it, now you can run your demo app and see the admob advertisement show up in your app!
(Note: It may take a while for the app to appear on the screen as it is being set up for the very first time, it should be faster in subsequent loads)

You can learn more Here:

Mobile Development using FLEX!

Adobe air has been creating buzz about being able to develop flex application in multiple platform pretty similar to Java. Now, with Adobe Air being available in mobile devices, possibility is endless. It will be interesting to see how far this will go. Specially, the devices with lot of hardware like accelerometer, gyroscope, GPS. (Hello Apple, will you someone day support Adobe Air?Ans: No, If you want adobe use Android!)

Android SDK – Changing background of a layout at run time

I was working on a android project where I had to change background image in a layout at at run time. For instance, the user selects an image and it becomes the background of the layout. It is fairly simple to do in Android. See below on how I achieved it:

I have a Frame Layout in which I have defined a background in my case the image file name is “wooden.png” so I have, ‘¬†android:background=”@drawable/wooden” ‘ in the layout definition.¬†By having this line in my layout, Android will use the wooden.png ¬†that is in the “drawable” directory as the background for the activity .

See below for xml extract:

<FrameLayout xmlns:android=""	android:id="@+id/main_layout"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="@drawable/wooden">

.. ...



In the code if I want to change the background I could achieve this by calling “setBackgroundResource” method on the layout.

See below for an example.


View mainLayout = findViewById(; // getting the layout

mainLayout.setBackgroundResource(R.drawable.stone); // changing the background to 'stone.png'




Gestures on Android SDK

I am working on a android project where I need to detect gestures like, fling, scroll etc.
I thought I would share on how I was able to achieve gesture detection.


Here are the main guts.

1. have to implement OnGestureListener (this contract will bind you to implement many methods including “onFling”)

2. You have to define a gesture detector:

 gestureDetector = new GestureDetector(this);          // initialize GestureDetector

3. That’s it now you can detect touch, fling etc.

import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;

public class SpinTheBottle extends Activity implements OnGestureListener{
private GestureDetector gestureDetector;

    public void onCreate(Bundle savedInstanceState) {
        gestureDetector = new GestureDetector(this);          // initialize GestureDetector

     public boolean onTouchEvent(final MotionEvent event){
    	          return gestureDetector.onTouchEvent(event); // bubble it up

     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		System.out.println("Fling Detected ##########################"); // terrible thing to do but for this demo, we can check the logcat to see how fling is detected
		System.out.println("e1.X: "+e1.getX() + " e1.Y: "+e1.getY()+" e2.X: "+e2.getX()+" e2.Y: "+ e2.getY());
		System.out.println("X Vel: "+ velocityX+ " Y Vel: "+ velocityY);
		return true;