How to encode / decode data in Android


Sometimes need to encode / decode some data. As example sometimes need to encode some data, …

Really simple way do it use Base64 Encoder, which has adding to Android SDK since API 8. This class contain methods for encoding and decoding the Base64 representation of binary data.

For work with Base64 Encoder in android need to add import

import android.util.Base64;

Code snippet:

String testValue = "Hello, world!";
        
byte[] encodeValue = Base64.encode(testValue.getBytes(), Base64.DEFAULT);      
byte[] decodeValue = Base64.decode(encodeValue, Base64.DEFAULT);
        
Log.d("TEST", "defaultValue = " + testValue);
Log.d("TEST", "encodeValue = " + new String(encodeValue));
Log.d("TEST", "decodeValue = " + new String(decodeValue));

Output:

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

References:
Base64 | Android Developers

CategoriesUncategorized

13 thoughts on “How to encode / decode data in Android

  1. Encoding is not the same thing as encryption. If you’re storing sensitive information, you should be encrypting, not simply Base64 encoding.

    1. Yes, certainly, use encrypting better for sensitive information. But Base64 really good and powerful tool, which can help some developers.

Leave a Reply

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