Making your Android apps crash-proof

      No Comments on Making your Android apps crash-proof
Image courtesy: Crittercism Website

Do you have an android app on the Play Store, and get lots of negative comments/feedback?

Most of the time, apps crash on the first interaction with the user. And that’s the reason most users are frustrated of even downloading your app, and that’s when most of the negative comments start pouring in.

Of course, you have to look for crashes everywhere in your app, but crashing on the first page itself, is a really really bad situation. When that happens, and the user leaves a bad comment, instead of sending you a support mail, you have no idea how to fix it. You have no idea about the user’s device, and other important information that would help you in determining the problem, and fixing it. And if you continue having such a build even for a week on the store, that puts a dent on your overall app reviews. People generally look at the first few reviews, and make a decision based on that, whether to try your app or not.

I have had an app on the store for years now, which I didn’t update for a long time. And finally, when I got the time to work on it again, I decided to integrate Crittercism SDK within my app, along with Google Analytics SDK.

The very first update with +Crittercism along with +Google Analytics , my inbox was flooded with crash reports. I was amazed at how many un-reported crashes my app had. I was living in the dark, as to what all problems users were having with my app. Crittercism logs had more information about the crashes than I could have asked for. They were pretty detailed, in terms of the user’s device name, and OS versions, the version of the application, and a device snapshot (Memory/Storage) when the crash occurred.

After about a week, I made the next update, and this time, the crash notifications reduced dramatically, although the number of users and the average usage of my app went up. From this, I can guess that the users who are still using my app are a happy lot. And that makes me happy as well.

I would strongly recommend integrating such a live error reporting tool into your apps to get live feedback for your apps. Specifically for Crittercism, there are free and paid plans. Currently, I am on the free plan, and it gives me the almost everything that I need to know to fix those random crashes. With paid plans, you have more reporting, which I think I don’t need right away. Receiving crash notifications is just the one part of Crittercism. They call this solution as a “Mobile Application Performance Management” solution. Rightly so?

Have you used Crittercism in your apps? Do you have anything to say?

Easy Video Chooser Library for Android

After I wrote the “Easy Image Chooser library for Android“, I thought I could easily extend this library to handle other things as well. For now, I have implemented the option of choosing/recording a video. And in the future, I am planning to extend this library for choosing other types of files.

Choosing videos, is again very similar to how the images are handled. Using this library, you would be also able to choose videos that reside in your Picasa albums on your phone. And this should work for all OSes and devices.

After processing, the library would return a ChosenVideo object, which would contain the original path to the video file, and 2 differently-sized thumbnails which you can directly use as a preview.

Here is how to use this library.

  • For capturing a video using the camera

videoChooserManager = new VideoChooserManager(this, ChooserType.REQUEST_CAPTURE_VIDEO);

  •  For choosing a video from the gallery

videoChooserManager = new VideoChooserManager(this, ChooserType.REQUEST_PICK_VIDEO);

  • On Activity Result, write this

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK &&
(requestCode == ChooserType.REQUEST_PICK_VIDEO ||
requestCode == ChooserType.REQUEST_CAPTURE_VIDEO)) {
videoChooserManager.submit(requestCode, data);

public void onVideoChosen(final ChosenVideo video) {
runOnUiThread(new Runnable() {
public void run() {
if (video != null) {
// Use the video
// video.getFilePathOriginal();
// video.getFileThumbnail();
// video.getFileThumbnailSmall();

public void onError(final String reason) {
runOnUiThread(new Runnable() {
public void run() {
// Show error message

Here’s the link to the Github project. Do let me know your thoughts and feedbacks, and also any bugs if you come across. I will try to fix them as soon as possible.

Easy Image Chooser Library for Android

      5 Comments on Easy Image Chooser Library for Android

In almost all the Android apps that I have worked on, there has been a requirement for choosing an image or taking a snap and using the device’s camera.

Taking a snap, is rather straightforward to implement, but choosing an image from your gallery is sometimes a hard nut to crack. And to implement this correctly, you would always end up writing a lot of code. Assuming that you want to target all OSes, devices, folders etc.

For example, choosing a picture from the Camera folder of your phone is nice and easy. But, if you want to have the user chose an image from one of his picasa web albums, which he has synced on his phone, you will find a dead-end. Well, almost.

For myself, I must have at-least rewritten the same code, multiple number of times. Of course, the platform should help us in achieving this seemingly straightforward feature with as less code as possible. But, right now, it’s not possible.

So, I thought of creating a library which anyone could integrate within one’s own app, without really worrying about the nitty-gritties and the bugs, to implement or add this feature into his app. And there’s more. Most of the time, you would need a scaled down version of the chosen image to show a preview or use it in a listview. This library would give you 3 sizes, as of now.

  1. Original Size
  2. Thumbnail Size
  3. Thumbnail Smaller Size
The sizes are dynamically calculated, based on the original size of the image. It’s pretty rough here, but I am looking forward to improve that part.
This version of the library is pretty basic. But, I would be working on improving this library to add more functionality in the future.
You can find more information about this library here.
By using this library in the current state, you could handle all these cases/special cases with just a few lines of code. An example of this is shown below.
1. For choosing an image from gallery

imageChooserManager = new ImageChooserManager(this, ChooserType.REQUEST_PICK_PICTURE);

2. For capturing a picture using your camera

imageChooserManager = new ImageChooserManager(this, ChooserType.REQUEST_CAPTURE_PICTURE);

3. On Activity result, do this:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK &&
(requestCode == ChooserType.
requestCode == ChooserType.
imageChooserManager.submit(requestCode, data);

4. Implement the ImageChooserListener interface and override these methods:

public void onImageChosen(final ChosenImage image) {
runOnUiThread(new Runnable() {
public void run() {
if (image != null) {
// Use the image
// image.getFilePathOriginal();
// image.getFileThumbnail();
// image.getFileThumbnailSmall();
public void onError(final String reason) {
runOnUiThread(new Runnable() {
public void run() {
// Show error message

That’s all you need to code. And the library takes care of handling all kinds of images, and also generates 2 thumbnails which you could directly use. Let me know if you need to add any new features or if you find a bug. I will try to address those as soon as humanly possible. If you would like to contribute to this project, drop me a mail.

Google Maps API v2 on Android

      6 Comments on Google Maps API v2 on Android
The Splash Screen

I don’t even remember when was the last time I did something with MapView on Android. I was aware of the new version 2 of the Google Maps API, but never got a chance to work on it until today.

There were initial hitches to setup the project. But, once the first steps were done, it was quite easy to build up a simple app.

I want to list down the first steps of the process, and then move on to the sample application.

Step 1: Getting the API key.

  1. Go to Google API Console
  2. Go to Services link, and enable Google Maps Android API v2. (Don’t confuse this with Google Maps API v2. I got confused, and was wondering what was I doing wrong when the maps failed to load)
  3. After enabling the service, go to the API Access link.
  4. In the Simple API access section, click on “Create New Android Key”.
  5. Enter your keystore’s SHA1 fingerprint along with your application’s package name separated by a semi-colon in the dialog and click on “Save”.
  6. Your API should be visible now on the same page.
Step 2: Setting up the project.
  1. You need to find the library project for the Google Maps API v2. It should be available in your SDK directory. If not, open up the Android SDK manager and download the same by selecting Google Play Services in the Extras section.
  2. You would find the required library project in the following location of the SDK folder. (
  3. My suggestion would be to make a copy of this project somewhere else, and then import the project into eclipse.
  4. Once imported into Eclipse, use this as a library project for your application.
Step 3: Setting up the manifest file.
  1. Your manifest file should look like this. AndroidManifest.xml
  2. You can change the package names for the permissions to use your own package name.
  3. Now, replace your API key with the place-holder API Key in the manifest.
Step 4: MapFragment and more code…
  1. To show a map, I used the MapFragment in the activity’s layout.
That’s it. These are the broad steps to configure the new version of Google Maps for your Android application.
Your Places
Add a new place
What this application does?
  1. On opening the application, you would see a splash screen, and it would try to get your current location.
  2. Once it gets your location, it would switch to the map view, and display your current location with a marker.
  3. Tapping on an unmarked area of the app, you would see a dialog, through which you can add a new place.
  4. After saving the new place by providing a name and a description, this place would be saved into the database and you would be able to see the newly added place on the map.
  5. Tapping on an already visible marker will show you the details of that place.
  6. The next time you open the application, all the previously stored places would appear on the map along with your current location.
Suggested optimizations
  1. While loading the points from the database, it would be nice if we can only load the places which are within the currently visible area of your app.
  2. When the map is re-sized or moved, we could re-query the database for the fresh list of places and update the markers based on the new visible area.
  1. The VisibleRegion API, currently, doesn’t work. Need to think of a workaround for this.

You can find the full source-code here at the github respository: android-map101-v2

Easier Bug Reporting on 4.2

      No Comments on Easier Bug Reporting on 4.2
With the recent release of an updated Jelly Bean version, i.e, 4.2, there have been quite some new things to awe you.

These are two things that could probably make a developers life easier.

  • Take bug report — immediately takes a screen shot and dumps device state information to local file storage, then attaches them to a new outgoing email message.
  • Power menu bug reports — Adds a new option to the device power menu and quick settings to take a bug report (see above).
Remember, while you were testing your app on a bus, or you were away from your desktop/laptop and got a dreaded crash!! You, so eagerly want to have a look at the logcat, or even save the logcat output for later investigation. And most of the times, I don’t have SendLog, which I could fire up, and send me the logs.
With 4.2, it’s already built-in to your phone. Here are a few screenshots, that give you an idea.
Enable this option from the Settings Page.

Hold the power button, to see the option to capture a “Bug Report”
Happy Coding…

Check orientation of images/captures

      4 Comments on Check orientation of images/captures
A lot of times, you would need your app to either pick an image from the gallery or use the device’s camera for capturing a picture that your app could use. I have seen a lot of apps, do it plain wrong. Especially, the orientation of the images.

The default gallery app, reads the orientation properly, and displays the images/thumbnails properly. So, our apps can also handle images in various orientations properly. And the good news is, it’s very easy to handle.

There’s a class called ExifInterface. Most of the times, when you have a similar situation, you would almost never want a full-scaled image to be shown in your app. Most often, we use a thumbnail view for the purpose. The following code would get you a re-sized bitmap, from your original file.

Say for example, we have this path to the actual image file. imagePath

1. Create a Bitmap from the file

Bitmap b = BitmapFactory.decodeFile(imagePath);

2. Resize the Bitmap by scaling it to appropriate level

int width = b.getWidth();
int height = b.getHeight();
int newWidth = 150;
int newHeight = 150;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// Bitmap resizedBitmap = Bitmap.createBitmap(b, 0, 0, width, height, matrix, true);
// resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, out);

3. Handle orientation of the image

ExifInterface exif = new ExifInterface(imagePath);
String orientation = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
if (orientation.equals(ExifInterface.ORIENTATION_NORMAL)) {
        // Do nothing. The original image is fine.
} else if (orientation.equals(ExifInterface.ORIENTATION_ROTATE_90+””)) {
} else if (orientation.equals(ExifInterface.ORIENTATION_ROTATE_180+””)) {
} else if (orientation.equals(ExifInterface.ORIENTATION_ROTATE_270+””)) {

4. Save the new bitmap 

out = new FileOutputStream(new File(“some output file path”));
Bitmap resizedBitmap = Bitmap.createBitmap(b, 0, 0, width, height, matrix, true);
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, out);

Now your output file would be an image that is resized and handled properly for orientation of the images. You could directly use the “resized” bitmap, but I prefere files.

Android Themes: A dialog without a title

Most of the times, I have seen developers not leveraging the power of themes and styles. Themes and styles are a great way to easily create UI that are  manageable and compatible for various platforms. Here’s the official documentation that explains styles and themes in details, and I consider this portion of documentation to be equally important to any developer working with Android.

For the example of this post, we will see how to make a dialog, a custom dialog, not to have a title. The easiest way to do this, is through code byt writing this snippet in your custom dialog class.


Dialog with Title on Android 2.2

Dialog with no title on Android 2.2

While this would work anyway, and would also be compatible with all the versions of Android. But, it’s a good idea to use more of your themes and styles in your programming, so that your code base is maintainable and your apps would behave and feel consistently. Using styles and themes makes it very easy to tweak or adapt to various platform versions and/or device sizes and resolutions. So, let’s get in.

The application tag, has a configurable attribute called “android:theme” with which you can set a theme to your application as a whole. You can also specify themes for individual themes for all your activities separately. Sounds nice!!! But, let’s stick to one theme for our application as a whole for simplicity.

For this example, we have a theme (it’s actually called a style), called MyThemeSelector as shown below. This is specified in the styles.xml in your values folder. Notice, your custom theme is a child of the Theme, which is one of the system’s default themes.

<resources>        <style name=”MyThemeSelector” parent=”@android:style/Theme”></style></resources>

Ideally, you should also declare your custom theme to extend one of the basic themes that are available with platforms on or above Honeycomb. For example, here we have created another styles.xml in a folder called values-v11, which looks like this.

        <style name=”MyThemeSelector” parent=”@android:style/Theme.DeviceDefault.Light”></style>

So, your basic theme is now compatible with both older versions and versions greater than Honeycomb. By this, I mean, that, when you run the app, your app would adapt to the platform that it is running on, and would give a consistent look and feel for your users.

Now, coming back to the main problem. “Creating a dialog without title”. Here also, we would use themes, as against code. Here are the two new themes that you would be declaring.

For values folder: (Platform versions older than Honeycomb)

<style name=”My.Theme.Dialog” parent=”@android:style/Theme.Dialog”>
            <item name=”android:windowNoTitle”>true</item>
<style name=”MyThemedDialog” parent=”@style/My.Theme.Dialog”></style>

For values-v11 folder: (Platform version for Honeycomb and above)

<style name=”My.Dialog.Theme” parent=”@android:style/Theme.DeviceDefault.Light.Dialog.NoActionBar”></style>
<style name=”MyThemedDialog” parent=”@style/My.Dialog.Theme”></style>

There’s a subtle difference between the two versions. Of course, other than the parent classes. In older platform versions, there wasn’t a version of the Dialog theme without a title bar. So, what we do here, is to extend the basic Dialog them, and overwrite an attribute, so that our custom “My.Theme.Dialog” is a dialog without a title bar.

But, for Honeycomb and above, the platform itself provides a version of the Dialog theme, without the title bar (or the Action Bar).

And finally, the last step for getting everything to work is set the theme to your dialogs.

MyDialog dialog = new MyDialog(this,;
dialog.setTitle(“Here’s my title”);; 

Why didn’t we use “My.Theme.Dialog” directly? Well, we could still try and tweak the theme for older versions, in the values folder, by adding a few more attributes.

Dialog with title on Android 4.1

Dialog with no title on Android 4.1

As you can see, for both older and newer platforms, the app runs by adapting itself and gives a consistent look and feel. You didn’t have to do much with your code. 
15 lines of XML is the MAGIC here!!!!  (I didn’t count though, just guessing)

Sample project here.

Sending SMS on Android and tracking it

      3 Comments on Sending SMS on Android and tracking it

Lets look at how to send an SMS. It’s pretty simple though. A few lines of code and your SMS is gone. To make it more convenient and meaningful, we should also be able to track and let the user know when the SMS is sent and when it is delivered. For a start, I won’t be looking into how to trap the error messages here and log or show it to the user. May be, when I get some more time, I will update this post. For now, lets track our SMS.

        Intent sentIntent = new Intent(INTENT_ACTION_SENT);
        PendingIntent pendingSentIntent = PendingIntent.getBroadcast(this,
                REQUEST_CODE_ACTION_SENT, sentIntent,

        Intent deliveryIntent = new Intent(INTENT_ACTION_DELIVERY);
        PendingIntent pendingDeliveryIntent = PendingIntent.getBroadcast(this,
                REQUEST_CODE_ACTION_DELIVERY, deliveryIntent,

        SmsManager smsManager = SmsManager.getDefault();

        // Second parameter is the service center number. Use null if you want
        // to use the default number
        smsManager.sendTextMessage(number, null, message, pendingSentIntent,

In the above code snipped, you can see that we are passing 2 pending intents to the SMSManager, one of which will be fired when the SMS is sent, and the other, when the SMS is delivered. It would also let you know the error type if the sending or delivery fails, so that you can take action for the errors. INTENT_ACTION_SENT and INTENT_ACTION_DELIVERY are string constants, which are just some random actions required to setup of the PendingIntents and receive them back.

Setting up the SMS is super easy. How do we track or listen to the updates, which happen through the PendingIntents? Well, those pending intents could be for starting an Activity, a Service or sending out a Broadcast. As you can see, here, I have used a Broadcast, to keep it simple. So, in our activity, we would need to register BroadcastReceivers for the same actions.

        IntentFilter filter = new IntentFilter(INTENT_ACTION_SENT);

        registerReceiver(smsSentDeliveredReceiver, filter);

Now, the onReceive() method will be fired, when those events happen, and thus you can notify the user about when the message is sent and delivered.

        String action = intent.getAction();
        Log.i(TAG, “Received: ” + action);

        if (action.equals(INTENT_ACTION_SENT)) {
            Log.i(TAG, “Message: Sent”);
            Toast.makeText(this, “Message sent”, Toast.LENGTH_LONG).show();
        } else if (action.equals(INTENT_ACTION_DELIVERY)) {
            Log.i(TAG, “Message: Delivered”);
            Toast.makeText(this, “Message delivered”, Toast.LENGTH_LONG).show();

You can find the sample app and the source code here. Give it a run.

Note: Using this example, you cannot send SMS to real numbers from an emulator. The SMS will be sent, but it will never be delivered.

Download Videos from Youtube Trick

      11 Comments on Download Videos from Youtube Trick

First things first. Is it legal to download videos from Youtube?

As much I have understood from the Terms of Service, it’s not a straight yes or no. Basically, Youtube doesn’t have a publicly available API or service that would allow users to download the videos. Of course, you can download back the videos that you had originally uploaded. But who would do that anyway?

However, there are workarounds and tricks with which you can actually download any video from the website. There are many softwares/add-ons that easily do this job. Here is a snapshot from the published “Terms of Service“.

You shall not download any Content unless you see a “download” or
similar link displayed by YouTube on the Service for that Content. You
shall not copy, reproduce, make available online or electronically
transmit, publish, adapt, distribute, transmit, broadcast, display,
sell, license, or otherwise exploit any Content for any other purposes
without the prior written consent of YouTube or the respective licensors
of the Content. YouTube and its licensors reserve all rights not
expressly granted in and to the Service and the Content.
From Youtube Terms of Service

It says, that you cannot exploit the content/content-owners by selling the videos or re-distributing it, thereby, making a profit against your sales. That’s obviously illegal for any kind of content, unless of course, the license makes that content freely re-distributable. So, if you download the videos using those workarounds and tricks, only for your personal use (ex, offline viewing), you probably aren’t breaking any rules. What about those add-ons/softwares that do this? Well, it’s not illegal for them, since they are just distributing the software. So, they are off the hook.

For personal use, it seems ok to download videos off from Youtube. So? let’s see how hard or difficult it is to get this working.Actually, it’s quite simple.

Step 1: You should have the VIDEO ID of the video that you want to download.

Step 2: You need to make a call to this api, to get the details for that video. The fmt parameter is for getting the specified format of the videos. See the “Quality and Codecs” section on this page on Wikipedia.

URL =>

Step 3: Process the response. You will get a plain string response. That response contains all the direct URLs to various formats of the video. Look for the key “url_encoded_fmt_stream_map” and the value for this key is what you need from this response. You will need to filter out all the URLs from here, and get hold of the URL to the format you want to download. Here are some sample URLs.,expire,ip,ipbits,itag,source,ratebypass,cp&fexp=904510,914501,908302,902315,916201,905267&itag=45&ip=; codecs=”vp8.0, vorbis”&itag=45,expire,ip,ipbits,itag,source,ratebypass,cp&fexp=904510,914501,908302,902315,916201,905267&itag=22&ip=; codecs=”avc1.64001F, mp4a.40.2″&itag=22

 If you notice the URLs, there is a type parameter, where you can determine which URL is for which format (type=video/mp4, type=video/webm etc).

Step 4: To finally be able to download the video, you need to strip off a few values from these URLs, just to make sure your calls don’t fail due to long URLs. What I have noticed is that if you strip off (everything after the quality param) the last parts of the URLs, everything’s just fine. So, the final URL would be something like:,expire,ip,ipbits,itag,source,ratebypass,cp&fexp=904510,914501,908302,902315,916201,905267&itag=22&ip=

Step 5: Save the file with the proper extension. That’s it. You are done.

If you ask how I got to know about this trick? Well, everything’s already out there on the web. A lot of people have already blogged about it before. But, I had to dig for it for almost 2 days. So, I hope someone finds it useful. So, if you want to make your own Youtube Downloader, now you know “How to Download Youtube Videos programmatically”. 

Note: This method might stop working as and when Google/Youtube blocks this loophole. In the past, Youtube has been known to block a few other workarounds that had existed.

Bluetooth on Android : Part I

      6 Comments on Bluetooth on Android : Part I
This is a part of a series of posts in which I will put forward a full working app what uses bluetooth on your Android device to discover, connect, pair, send and receive files. The source code would be tagged with each part of this series.

Part 1: The app should be able to discover and list out the devices (paired/unpaired).

To start off with learning about bluetooth on Android, visit the official documentation. The documentation is quite lucid and clear. Here I will try to explain parts of my code.

The first activity (HomeActivity), for now, will have a single button “Discover Devices”, which will take you to the activity(DiscoverDevicesActivity) where you can see the list of devices that are visible by your device.

This activity does a few things, quite a few if-else conditions.

  • First, you need to check if your device supports bluetooth. If you don’t have the hardware capability on your phone, you won’t be able to run this application. Eh!! Most of the phones would obviously have bluetooth. Ummm…Yes… But the emulators don’t. Arrggghhh!!!!
  • Once you are sure that your device has bluetooth capability, the next thing to check if it is enabled or not. If it’s enabled, move on to the next step, else you will need to turn it on first.
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(intent, REQUEST_ENABLE_BT);

  • Once, you click on “Yes” on the confirmation dialog that you will see, bluetooth radio will be switched on for you. On the screen, the “Scan” button will become active. Once you tap the “Scan” button, the ListView will show the list of devices that your device can discover.

That’s all for the first part of the series. But, there’s a little more to understand abut discovery.

The process of discovery is asynchronous. The list view, currently shows two kinds of devices.

  1. Devices which your phone already knows about (Paired)
  2. Devices which are discovered (Which are not paired with your device)

Getting the already paired devices is simple. The BluetoothAdapter will give you details about such devices.

// Check already discovered devices

Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : devices) {

Now comes the actual discovery part. For this, you will need to register a broadcast receiver which will be called whenever a new device is found. After registering the receiver, you need to trigger the discovery by calling the startDiscovery() method of the BluetoothAdapter.

// Scan for new devices
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(devicesReceiver, filter);


On the receiver’s onReceive() method, we pick up the details about the new device found, and add it to our ListView.

public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      // When discovery finds a device
      if (BluetoothDevice.ACTION_FOUND.equals(action)) {
          Log.i(TAG, “Device found”);
          // Get the BluetoothDevice object from the Intent
          BluetoothDevice device = intent
          // Add the name and address to an array adapter to show in a ListView


The DevicesAdapter is a custom adapter for the ListView which we will be updating in the subsequent posts to show more information about the devices.

As always, you should unregister your receiver, once your activity is paused. Also, in addition to this, you should also cancel the discovery if at all you have started by calling the cancelDiscovery() method of the BluetoothAdapter.

The part 1 of the project can be checked out by fetching the source code and checking out the v1.0 tag from the repository. The complete source code can be found here.

Alternately, if you want to download the source of Part 1 as a zip, use this link to Part 1.