Activity.startActivityForResult – not calling onActivityResult

I implemented a quick button to look up an image using the installed Android Gallery app:


    public void btnPickImage(View v) {
      Intent intent = new Intent();
      intent.setAction(Intent.ACTION_GET_CONTENT);
      intent.setType("image/*");
      startActivityForResult(intent, REQUEST_IMAGE);
    }

And then, to get the Uri of the image selected by the user:


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      switch (requestCode) {
      case REQUEST_IMAGE:
        if ( resultCode == Activity.RESULT_OK ) {
          Uri image = data.getData();
          // Do something with the image now...
        }
        break;
      }
    }

The code opens the gallery and allows for selection of an image. Once selected, the gallery Activity closes and returns to my Activity.

But, onActivityResult was not getting called!!!

Now, if the Gallery was one of my own Activities, then I’d guess I was neglecting to call setResult() and finish() correctly.

Or that I was using startActivity() instead of startActivityForResult().

The problem, it turns out is that my requestCode was defined as:


   private static final int REQUEST_IMAGE = -69;   // Does not work!!!

And Android interprets the negative value requestCode as a plain old startActivity() instead of startActivityForResult().

The moral of the story is that we should always use positive values for requestCodes…


   private static final int REQUEST_IMAGE = 69;   // Works just fine!!!
Posted in Android | Tagged | Leave a comment

Discovering Android – GSON woes on MyTouch 4G – Android 2.2.1

I’m developing an application using GSON for use with JSON-based Restful web services. Now it didn’t seem like it at the time, but there turns out that there is a conflict between HTC’s 2.2.1 release of Android and *ANY* app using GSON library.

The symptom you’ll get will be a “Unable to find Type: your.fully.qualified.ClassName” error message from an underlying TypeNotPresentException. This will likely drive you batty.

For me, the class it couldn’t find was in a third-party jar and I assumed the application was unable to access classes from this jar. I eventually moved the source for the third-party jar into my own project and thought my work was done. Alas, I still got the TypeNotPresentException.

Well, after much searching I eventually stumbled upon the actual problem and eventual solution.

You see, the HTC guys have included GSON themselves as a *public* jar. So, the classes for GSON are already loaded by a classloader which has NO IDEA ABOUT THE CLASSES YOU’RE USING. That’s why no matter what you do, the classes cannot be found once GSON tries to access them.

The work around for this is to use jarjar which will allow you to change the namespace of the GSON classes and use them explicitly, thus avoiding the publicly defined preloaded classes. Here’s a great explanation of how to use jarjar in this specific case.

Posted in Uncategorized | Tagged | Leave a comment

Discovering Android – flash_image not found?!?

If you are needing to use the “flash_image” utility program ( perhaps to get ClockworkMod3 on your system? perhaps because you need want to update to CyanogenMod7? ) and you get a “not found” message when you go to run it like this:

$ su
# flash_image
flash_image: not found

Here’s a link where you can get the program : flash_image

Once you download it you can copy it out to your phone via adb as such:

adb push flash_image /system/bin

Posted in Uncategorized | Tagged | Leave a comment

Discovering Android – ADB su – Permission Denied

If you are using adb and attempt to get root access by running ‘su’ and instead get the message “Permission Denied”, then there are two things you must make sure you’ve done.

1. Make sure you have rooted your phone. This is complicated and I won’t go into it here – it differs based on what phone model you have. Search XDA for advice.
2. Make sure you’ve explicitly given the adb process attached to your phone access to root.

So, even after you root your phone, when you then connect via adb it will prompt you ON THE PHONE to allow access.
su root request - click "Allow"

Click “Allow” and then you’re good as gold.

Posted in Uncategorized | Leave a comment

Discovering Android – ADB Woes – Can’t cd to sdcard

If you are using ADB tools to work on your phone but having problems accessing the sdcard, then it isn’t enough to just unmount the drive from your pc.

To remedy this you must put your phone into “Charge Only” mode before connecting it to your pc. To do this you need to go to “Settings->Connect To PC->Default Connection Type” and select “Charge Only”. Other options here are “Disk Drive” and “USB Tethering”. Once you’ve done this you’ll be able to run “adb shell” and then your attempt to run “cd sdcard” will succeed.

Posted in Uncategorized | Leave a comment

Discovering Android – Opening A Progress Dialog with AsyncTask

There are 3 important methods to override in AsyncTask.

1. doInBackground : this is where the meat of your background processing will occur.
2. onPreExecute : show your ProgressDialog here ( showDialog )
3. onPostExecute : hide your ProgressDialog here ( removeDialog or dismissDialog )

If you make your AsyncTask subclass as an inner class of your activity, then you can call the framework methods showDialog, dismissDialog, and removeDialog from within your AsyncActivity.

Here’s a sample implementation of AsyncTask:


class LoginProgressTask extends AsyncTask {
    @Override
    protected Boolean doInBackground(String... params) {
        try {
            Thread.sleep(4000);  // Do your real work here
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Boolean.TRUE;   // Return your real result here
    }

    @Override
    protected void onPreExecute() {
        showDialog(AUTHORIZING_DIALOG);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // result is the value returned from doInBackground
        removeDialog(AUTHORIZING_DIALOG);
        Intent i = new Intent(HelloAndroid.this, LandingActivity.class);
        startActivity(i);
    }
}
Posted in Uncategorized | Tagged | Leave a comment

Discovering Android – Embedding Video in an Android Application

I was putting some Video into an Android application for the first time. I was hoping this wouldn’t be too difficult and was delighted to find the VideoView component. It was really simple to add a VideoView to my layout:


<VideoView android:layout_height="wrap_content"
		android:layout_width="wrap_content"
		android:id="@+id/videoView"/>

Then I prepared the video and added it to my project as follows:
1) Convert your video to either gp3, mp4 or wmv format. (Yeah, wmv works surprisingly. avi and flv do not work ).
2) Copy the video into your project’s res/raw folder. For example’s sake, I’ll say the video I copied there is named “my_video.mp4
** Android will detect this and create a static resource ID for you named R.raw.my_video – you will use this (and not the file name) when building the URI to play your video.
3) Add code in my Activity that would lookup the VideoView, set the URI and start the player:


        VideoView vv = (VideoView)this.findViewById(R.id.videoView);
        String fileName = "android.resource://" + getPackageName() + "/" + R.raw.my_video;
        vv.setVideoURI(Uri.parse(fileName));
        vv.start();

There you have it…

Posted in Uncategorized | Tagged | Leave a comment

Discovering Android – New SDK r9 and ADT 9.0 Install Difficulty

I was so excited to get the new ADT installed and try out all of it’s new features that I was updating the ADT through eclipse and the SDK through the SDK Manager. The SDK Manager threw up this message box: A folder failed to be renamed or moved.  On windows this typically means that a program is using that folder...Please momentarily deactivate your anti-virus software.  Please also close any running programs that may be accessing the directory ..\platform-tools.  When ready press YES to try again.
On windows this typically means that a program is using that folder…Please momentarily deactivate your anti-virus software.
Well, this was the most awesome error message I’d ever gotten. So, I went to my task manager to look for some unknown background anti-virus that may have come pre-installed on my system. I didn’t find anything, but closed a couple seemingly extraneous tasks. Closing these tasks did not help. But I was able to click YES and try again. And again.
Please also close any running programs that may be accessing the directory ..\platform-tools.
Long story short, it was Eclipse’s ADT that had a handle on the platform-tools directory. Closing Eclipse allowed the SDK manager to continue with its update :) This friendly error message dialog that let me troubleshoot the problem and click YES until I got it saved me a lot of time and headache. Thanks for the nice update installer logic!

Posted in Uncategorized | Tagged | Leave a comment

Discovering Android – Running on a Physical Device

The Eclipse ADT plugin for Android is awesome and provides a nice emulator which can approximate a number of different API and Hardware versions. What’s even cooler is that you plug your own Android Device (Phone) into your computer via USB and run/debug your code directly on it. The result of this is that you get a much faster startup time and a more tactile, realistic idea of what your application will be like.

To do this you must first install the Android USB drivers for your OS. Once you’ve installed the drivers, you are almost ready.

Once your drivers are installed, plug your phone in via a USB cable. But before you start trying to run your code on it, let’s first open the Devices view within Eclipse. To do this select menu Window->Show View->Other, and then Android->Devices. You should see the device listed here.

Device recognized and online

Device recognized and online

If instead your device is shown as offline:

Device detected but offline

Device detected but offline


then you need to make sure you are not plugged into a USB hub. I know this sounds nuts ( I thought it did, too ), but on my machine, even using the front ports on my case kept my device offline. When I plugged into the direct motherboard port at the rear of the machine it then became online. I encountered this problem on Windows 7.

Now that your device is detected and online, running your project on your phone is a snap. Just right-click on your project and select either “run as” or “debug as” and then select “Android Application”. The ADT plugin will copy the files to your phone and start the application up immediately. If you chose to debug, then your breakpoints will function as you’d expect, but only after you’ve altered the AndroidManifest.xml to explicitly allow debugging.

Tagged | Leave a comment

Discovering Android – Getting Started

I’ve been going through Android and learning how to do all of the basics. I’ll be posting specifics in the coming weeks, but for starters I want to talk briefly about the development environment.

I’m using Eclipse with the ADT plugin.

In addition to the ADT plugin, you’ll also need the Android SDK installed on your machine.

Once they are both installed be sure to update your ADT preferences in Eclipse to point to the location of the SDK. To do this select from the menu: Windows->Preferences->Android and browse to the correct SDK location.

Hello world is as easy as selecting File->New->Project and then selecting Android->Android Project. Get your Hello World app running and tune back in for more soon.

Tagged | Leave a comment