Encoding/Decoding

How to encode / decode data in Android

Alex Zhukovich 1 min read
How to encode / decode data in Android
Table of Contents

Sometimes need to encode/decode some data. A simple way to do it is to use Base64 Encoder, which is available in Android SDK since API 8. This class contains methods for encoding and decoding the Base64 representation of binary data.

We can use the following code to encode/decode any String value.

import android.util.Base64;

...

String testValue = "Hello, world!";

byte[] encodeValue = Base64.encode(testValue.getBytes(), Base64.DEFAULT);
byte[] decodeValue = Base64.decode(encodeValue, Base64.DEFAULT);

Log.d("ENCODE_DECODE", "defaultValue = " + testValue);
Log.d("ENCODE_DECODE", "encodeValue = " + new String(encodeValue));
Log.d("ENCODE_DECODE", "decodeValue = " + new String(decodeValue));


Output:

defaultValue = Hello, world!
encodeValue = SGVsbG8sIHdvcmxkIQ==
decodeValue = Hello, world!


References:


Mobile development with Alex

A blog about Android development & testing, Best Practices, Tips and Tricks

Share

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Mobile development with Alex.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.