Base64 Encoding in Android 2.1 or Earlier

Base64 is common used. Now Google added a utility class android.util.Base64. Unfortunately it is only available in Android 2.2 and later.

So, you need just a little bit work to use it with Android 2.1 or ealier. Yes, just copy and past the source of Base64 into your project. Make sure to preserve the Apache 2.0 license section, in order to conform to the license. The source code is provided at the end of this post, for your reference.

My disclaimer: I am not responsible for any result in doing the practice described hereby. Read the license if you need.

Now let’s see example usage:

The output is:

Encoded: dGhpcyBpcyBhIG1lc3NhZ2UgYnkgZnJhbmsu

Decoded: this is a message by frank.

Let’s try decode the message in python:

You will get the same input message htere. Now you are ready to send your data to anywhere, like app engine, you know!


The android.util.Base64 source

This entry was posted in android, java, python and tagged , , . Bookmark the permalink.

3 Responses to Base64 Encoding in Android 2.1 or Earlier

  1. Frank says:

    The Base64 code crashes when trying to decode. The line

    String decoded = new String(Base64.decode(encoded, Base64.DEFAULT));

    gives no errors in Eclipse, but the app crashes in the Android emulator (2.1).

  2. Frank says:

    Ups. I saw the problem now: You for got to add .getBytes. The correct line should be

    String decoded = new String(Base64.decode(encoded.getBytes(), Base64.DEFAULT));

  3. frank says:

    @Frank: I don’t see an error here, because Base64.decode() method support both String and byte array as 1st argument. Probably the string is null?

Leave a Reply

Your email address will not be published. Required fields are marked *

ERROR: si-captcha.php plugin: GD image support not detected in PHP!

Contact your web host and ask them to enable GD image support for PHP.

ERROR: si-captcha.php plugin: imagepng function not detected in PHP!

Contact your web host and ask them to enable imagepng for PHP.