Base64 support for different API levels

Solution 1:

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:

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:

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:

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;
    }