Base64 support for different API levels

AndroidBase64Kotlin

Android Problem Overview


In my Android app

build.gradle

android {
    compileSdkVersion 27
    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 27
        ...
        }
    ....
}

Kotlin code

val data = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    Base64.getDecoder().decode(str)
} else {
    Base64.decode(str, Base64.DEFAULT) // Unresolved reference: decode
}

Obviously, I got compilation error, when using Base64 variant prior to API 24.

But how can I support all the API levels and use Base64 as before 24, as after?

Android Solutions


Solution 1 - Android

Use android.util.Base64 will resolve your problem its available from API 8

data = android.util.Base64.decode(str, android.util.Base64.DEFAULT);

Example usage:

Log.i(TAG, "data: " + new String(data));

Solution 2 - Android

fun String.toBase64(): String {
    return String(
        android.util.Base64.encode(this.toByteArray(), android.util.Base64.DEFAULT),
        StandardCharsets.UTF_8
    )
}


fun String.fromBase64(): String {
    return String(
        android.util.Base64.decode(this, android.util.Base64.DEFAULT),
        StandardCharsets.UTF_8
    )
}

Solution 3 - Android

You should be using the android.util.Base64 class. It is supported from API 8,

The Base64.getDecoder() function is part of java.util.Base64 and new in Java8.

Solution 4 - Android

private String encodeFromImage() {
        String encode = null;
        if (imageView.getVisibility() == View.VISIBLE) {
            Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            //encode = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);
            //String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap,"Title",null);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                encode = Base64.getEncoder().encodeToString(stream.toByteArray());
            } else {
                encode = android.util.Base64.encodeToString(stream.toByteArray(), android.util.Base64.DEFAULT);
            }
        }
        return encode;
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexeyView Question on Stackoverflow
Solution 1 - AndroidAbhishek SinghView Answer on Stackoverflow
Solution 2 - AndroidnorbDEVView Answer on Stackoverflow
Solution 3 - AndroidAshish MathewView Answer on Stackoverflow
Solution 4 - AndroidMustofa KamalView Answer on Stackoverflow