Duct Tape: Android common problems & their fixes

Duct Tape: Android common problems & their fixes

Overview:

Dive into a comprehensive collection of common Android development problems and their solutions, gathered from over five years of hands-on experience in software engineering. This resource is designed to provide quick and easy reference for developers facing similar challenges. Each problem is clearly outlined, making it easy to identify and understand the issue at hand.

Visual guides and illustrations accompany many of the problems, providing a deeper understanding of the concepts and solutions. For certain issues, you'll find links to gist code that offers quick fixes and workarounds.

DT-001: Base64 Image string corrupted when uploaded via POST body

TL:DR; USE Base64.NO_WRAP flag

When I was trying to upload a bitmap image converted to base64 string, and sent as POST body, it was getting corrupted. Base64 image string is too long, so I could not see using the problem with logger.

So I decided to intercept the request body using Charles. You need to setup the manual proxy settings of the android studio with your IP and port number 8888 (default for charles). After catching the request body, I found out that Base64 had numerous \n at certain pattern. Then, after digging some stack overflow, I figured out that, new line will be generated by default to accommodate some older programming language.

And, when it is passed through my ok http client, it gets \n for each new line. To solve this problem, I had to add a flag Base64.NO_WRAP flag when converting the image to base64

fun bitmapToBase64(bitmap: Bitmap): String {
    val byteStream = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, byteStream)
    val b: ByteArray = byteStream.toByteArray()

    return Base64.encodeToString(b, Base64.NO_WRAP)
}

To be continued...