<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nishikanto Sarkar on Medium]]></title>
        <description><![CDATA[Stories by Nishikanto Sarkar on Medium]]></description>
        <link>https://medium.com/@nishikanto.abm?source=rss-b3f9e482bf1e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Q9q7Q9ospBcc5MoJ7lwWJQ.png</url>
            <title>Stories by Nishikanto Sarkar on Medium</title>
            <link>https://medium.com/@nishikanto.abm?source=rss-b3f9e482bf1e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 10:45:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nishikanto.abm/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Generating Custom QR Codes in Android with Kotlin: A Technical Guide]]></title>
            <link>https://medium.com/@nishikanto.abm/generating-custom-qr-codes-in-android-with-kotlin-a-technical-guide-a0adb06757d4?source=rss-b3f9e482bf1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0adb06757d4</guid>
            <category><![CDATA[qr-code-genrator]]></category>
            <category><![CDATA[qr-code]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <dc:creator><![CDATA[Nishikanto Sarkar]]></dc:creator>
            <pubDate>Thu, 22 May 2025 08:54:17 GMT</pubDate>
            <atom:updated>2025-05-22T08:54:17.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vArEVi7AJuXQ0X5G-DDXUg.png" /></figure><h3>Overview</h3><p>This Kotlin implementation creates customizable QR codes for Android, leveraging ZXing for encoding and Jetpack Compose for rendering. It supports styled modules, logo overlays, and background images, optimized for flexibility and scannability.</p><h3>QrCodeGenerator Interface</h3><p>Defines a suspend function for generating QR code bitmaps.</p><pre>interface QrCodeGenerator {<br>    suspend fun generateQrBitmap(config: QrStyleConfig): QrImageResult<br>}</pre><h3>QrStyleConfig Data Class</h3><p>Configures QR code generation with properties for text, dimensions, colors, and styles.</p><pre>data class QrStyleConfig(<br>    val preparedText: String,<br>    val width: Int = 1024,<br>    val height: Int = 1024,<br>    val qrColor: Int = 0xFF000000.toInt(), // ARGB black<br>    val logoBgColor: Int = 0xFFFFFFFF.toInt(), // white<br>    val qrVisualCategory: QrVisualCategory = QrVisualCategory.STANDARD,<br>    val logoUri: String? = null,<br>    val backgroundUri: String? = null<br>)</pre><h3>QrImageResult Sealed Class</h3><p>Represents generation results: success with a bitmap or failure.</p><pre>sealed class QrImageResult {<br>    data class Android(val bitmap: ImageBitmap) : QrImageResult()<br>    data object Error : QrImageResult()<br>}</pre><h3>QrCodeGeneratorImpl Class</h3><p>Implements <strong>QrCodeGenerator</strong>, requiring an Android Context. Key methods:</p><ul><li><strong>generateQrCode</strong>: Generates QR code bitmap.</li><li><strong>drawFinderPatternCircleStyle</strong>: Draws circular finder patterns.</li><li><strong>decodeBackgroundBitmap</strong>: Decodes images from URIs.</li><li><strong>overlayBackground</strong>: Overlays QR code on background.</li><li><strong>generateQrBitmap</strong>: Returns <strong>QrImageResult</strong>.</li></ul><pre>import android.content.Context<br>import android.graphics.*<br>import android.net.Uri<br>import android.os.Build<br>import android.provider.MediaStore<br>import androidx.compose.ui.graphics.asImageBitmap<br>import androidx.core.graphics.createBitmap<br>import androidx.core.graphics.scale<br>import com.google.zxing.BarcodeFormat<br>import com.google.zxing.EncodeHintType<br>import com.google.zxing.qrcode.QRCodeWriter<br>import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel<br>import androidx.core.net.toUri<br>import com.caplyptasapps.qrcodegeneratorkmp.qrcodeutility.QrCodeGenerator<br>import com.caplyptasapps.qrcodegeneratorkmp.qrcodeutility.QrImageResult<br>import com.caplyptasapps.qrcodegeneratorkmp.qrcodeutility.QrStyleConfig<br>import com.caplyptasapps.qrcodegeneratorkmp.qrcodeutility.QrVisualCategory<br><br>/**<br> * Implementation of the QrCodeGenerator interface for generating QR codes with various styles.<br> *<br> * @param context The Android context used for resource access and bitmap decoding.<br> */<br>class QrCodeGeneratorImpl(private val context: Context) : QrCodeGenerator {<br><br>    companion object {<br>        private const val MIN_MODULE_SIZE = 4 // Minimum size in pixels for each module<br>    }<br><br>    /**<br>     * Generates a QR code bitmap based on the provided style configuration.<br>     *<br>     * @param qrCodeStyle The configuration for the QR code, including size, color, and visual style.<br>     * @return A Bitmap representing the generated QR code, or null if the input text is empty.<br>     */<br>    private fun generateQrCode(qrCodeStyle: QrStyleConfig): Bitmap? {<br>        val text = qrCodeStyle.preparedText<br>        if (text.isEmpty()) return null<br><br>        // QR code generation hints<br>        val hints = mapOf(<br>            EncodeHintType.ERROR_CORRECTION to ErrorCorrectionLevel.H, // High error correction<br>            EncodeHintType.MARGIN to 1<br>        )<br><br>        // Generate the QR code matrix<br>        val bitMatrix = QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, 0, 0, hints)<br>        val inputWidth = bitMatrix.width<br>        val inputHeight = bitMatrix.height<br><br>        // Calculate dimensions and scaling<br>        val quietZone = 1<br>        val qrWidth = inputWidth + 2 * quietZone<br>        val qrHeight = inputHeight + 2 * quietZone<br>        val multiple = maxOf(<br>            MIN_MODULE_SIZE,<br>            minOf(qrCodeStyle.width / qrWidth, qrCodeStyle.height / qrHeight)<br>        )<br><br>        val leftPadding = (qrCodeStyle.width - (inputWidth * multiple)) / 2f<br>        val topPadding = (qrCodeStyle.height - (inputHeight * multiple)) / 2f<br><br>        // Create a blank bitmap and canvas<br>        val bitmap = createBitmap(qrCodeStyle.width, qrCodeStyle.height)<br>        val canvas = Canvas(bitmap)<br>        canvas.drawColor(Color.TRANSPARENT)<br><br>        // Paint configuration for drawing QR code modules<br>        val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {<br>            color = qrCodeStyle.qrColor<br>            style = Paint.Style.FILL<br>        }<br><br>        // Adjusted radius for rounded dots<br>        val radius = multiple * 0.45f<br>        val eyeSize = 8<br><br>        // Determine the visual category of the QR code<br>        val category = try {<br>            qrCodeStyle.qrVisualCategory<br>        } catch (e: Exception) {<br>            QrVisualCategory.STANDARD<br>        }<br><br>        // Draw finder patterns (corner eyes) for multi-cornered eyes style<br>        if (category == QrVisualCategory.MULTI_CORNERED_EYES) {<br>            val diameter = multiple * eyeSize<br>            val offset = diameter * 0.05f<br>            drawFinderPatternCircleStyle(<br>                canvas,<br>                paint,<br>                leftPadding + offset,<br>                topPadding + offset,<br>                diameter,<br>                qrCodeStyle.qrColor,<br>            )<br>            drawFinderPatternCircleStyle(<br>                canvas,<br>                paint,<br>                leftPadding + (inputWidth - eyeSize) * multiple - offset,<br>                topPadding + offset,<br>                diameter,<br>                qrCodeStyle.qrColor,<br>            )<br>            drawFinderPatternCircleStyle(<br>                canvas,<br>                paint,<br>                leftPadding + offset,<br>                topPadding + (inputHeight - eyeSize) * multiple - offset,<br>                diameter,<br>                qrCodeStyle.qrColor,<br>            )<br>        }<br><br>        // Track filled cells for advanced rendering<br>        val filledMatrix = Array(inputWidth) { BooleanArray(inputHeight) }<br>        for (x in 0 until inputWidth) {<br>            for (y in 0 until inputHeight) {<br>                filledMatrix[x][y] = bitMatrix[x, y]<br>            }<br>        }<br><br>        // Draw the QR code modules based on the visual category<br>        for (x in 0 until inputWidth) {<br>            for (y in 0 until inputHeight) {<br>                if (!bitMatrix[x, y]) continue<br><br>                val isInTopLeftEye = x &lt; eyeSize &amp;&amp; y &lt; eyeSize<br>                val isInTopRightEye = x &gt;= inputWidth - eyeSize &amp;&amp; y &lt; eyeSize<br>                val isInBottomLeftEye = x &lt; eyeSize &amp;&amp; y &gt;= inputHeight - eyeSize<br><br>                // Skip finder pattern cells for special eyes style<br>                if (category == QrVisualCategory.MULTI_CORNERED_EYES &amp;&amp;<br>                    (isInTopLeftEye || isInTopRightEye || isInBottomLeftEye)<br>                ) continue<br><br>                val left = leftPadding + x * multiple<br>                val top = topPadding + y * multiple<br>                val right = left + multiple<br>                val bottom = top + multiple<br>                val cx = left + multiple / 2<br>                val cy = top + multiple / 2<br><br>                // Render modules based on the visual category<br>                when (category) {<br>                    QrVisualCategory.STANDARD -&gt; {<br>                        canvas.drawRect(left, top, right, bottom, paint)<br>                    }<br>                    QrVisualCategory.ROUNDED_DOTS -&gt; {<br>                        canvas.drawCircle(cx, cy, radius, paint)<br>                    }<br>                    QrVisualCategory.CHECKERBOARD -&gt; {<br>                        if ((x + y) % 2 == 0) {<br>                            canvas.drawRect(<br>                                left + multiple * 0.1f, top + multiple * 0.1f,<br>                                right - multiple * 0.1f, bottom - multiple * 0.1f, paint<br>                            )<br>                        } else {<br>                            canvas.drawCircle(cx, cy, radius * 0.9f, paint)<br>                        }<br>                    }<br>                    QrVisualCategory.ANGULAR_BLOCKY -&gt; {<br>                        val pad = multiple * 0.15f<br>                        canvas.drawRect(left + pad, top + pad, right - pad, bottom - pad, paint)<br>                    }<br>                    QrVisualCategory.MINI_ROUNDED_BLOCKS -&gt; {<br>                        val cornerRadius = multiple * 0.25f<br>                        canvas.drawRoundRect(<br>                            left + multiple * 0.05f,<br>                            top + multiple * 0.05f,<br>                            right - multiple * 0.05f,<br>                            bottom - multiple * 0.05f,<br>                            cornerRadius,<br>                            cornerRadius,<br>                            paint<br>                        )<br>                    }<br>                    QrVisualCategory.DENSE_PATTERN -&gt; {<br>                        val hasLeft = x &gt; 0 &amp;&amp; filledMatrix[x - 1][y]<br>                        val hasRight = x &lt; inputWidth - 1 &amp;&amp; filledMatrix[x + 1][y]<br>                        val hasTop = y &gt; 0 &amp;&amp; filledMatrix[x][y - 1]<br>                        val hasBottom = y &lt; inputHeight - 1 &amp;&amp; filledMatrix[x][y + 1]<br><br>                        canvas.drawCircle(cx, cy, radius * 0.9f, paint)<br><br>                        if (hasLeft) {<br>                            canvas.drawRect(left, cy - radius * 0.4f, cx, cy + radius * 0.4f, paint)<br>                        }<br>                        if (hasRight) {<br>                            canvas.drawRect(<br>                                cx,<br>                                cy - radius * 0.4f,<br>                                right,<br>                                cy + radius * 0.4f,<br>                                paint<br>                            )<br>                        }<br>                        if (hasTop) {<br>                            canvas.drawRect(cx - radius * 0.4f, top, cx + radius * 0.4f, cy, paint)<br>                        }<br>                        if (hasBottom) {<br>                            canvas.drawRect(<br>                                cx - radius * 0.4f,<br>                                cy,<br>                                cx + radius * 0.4f,<br>                                bottom,<br>                                paint<br>                            )<br>                        }<br>                    }<br>                    QrVisualCategory.SKEWED_OFF_GRID -&gt; {<br>                        val offsetX = if ((x + y) % 2 == 0) -multiple * 0.15f else multiple * 0.15f<br>                        val offsetY = if ((x - y) % 2 == 0) -multiple * 0.15f else multiple * 0.15f<br>                        canvas.drawRect(<br>                            left + offsetX,<br>                            top + offsetY,<br>                            right + offsetX,<br>                            bottom + offsetY,<br>                            paint<br>                        )<br>                    }<br>                    QrVisualCategory.MULTI_CORNERED_EYES -&gt; {<br>                        canvas.drawRect(left, top, right, bottom, paint)<br>                    }<br>                }<br>            }<br>        }<br><br>        // Add a logo to the center of the QR code if specified<br>        qrCodeStyle.logoUri?.let {<br>            val scaledLogo =<br>                decodeBackgroundBitmap(context, it.toUri()).scale(<br>                    qrCodeStyle.width / 5,<br>                    qrCodeStyle.height / 5<br>                )<br>            val centerX = (qrCodeStyle.width - scaledLogo.width) / 2f<br>            val centerY = (qrCodeStyle.height - scaledLogo.height) / 2f<br><br>            val bgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {<br>                color = qrCodeStyle.logoBgColor<br>                style = Paint.Style.FILL<br>            }<br><br>            canvas.drawRoundRect(<br>                centerX - 8f, centerY - 8f,<br>                centerX + scaledLogo.width + 8f,<br>                centerY + scaledLogo.height + 8f,<br>                16f, 16f,<br>                bgPaint<br>            )<br><br>            canvas.drawBitmap(scaledLogo, centerX, centerY, null)<br>        }<br><br>        // Overlay a background image if specified<br>        qrCodeStyle.backgroundUri?.let {<br>            val backgroundBitmap = decodeBackgroundBitmap(context, it.toUri())<br>            return overlayBackground(bitmap, backgroundBitmap)<br>        }<br><br>        return bitmap<br>    }<br><br>    /**<br>     * Draws a circular finder pattern for multi-cornered eyes style.<br>     *<br>     * @param canvas The canvas to draw on.<br>     * @param paint The paint used for drawing.<br>     * @param x The x-coordinate of the top-left corner of the pattern.<br>     * @param y The y-coordinate of the top-left corner of the pattern.<br>     * @param diameter The diameter of the outer circle.<br>     * @param qrColor The color of the QR code.<br>     */<br>    private fun drawFinderPatternCircleStyle(<br>        canvas: Canvas,<br>        paint: Paint,<br>        x: Float,<br>        y: Float,<br>        diameter: Int,<br>        qrColor: Int,<br>    ) {<br>        val whiteDiameter = diameter * 5f / 7f<br>        val whiteOffset = diameter / 7f<br>        val middleDiameter = diameter * 3f / 7f<br>        val middleOffset = diameter * 2f / 7f<br><br>        val clearPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {<br>            xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)<br>        }<br><br>        // Outer black circle<br>        paint.color = qrColor<br>        canvas.drawOval(<br>            RectF(<br>                x,<br>                y,<br>                x + diameter,<br>                y + diameter<br>            ),<br>            paint<br>        )<br><br>        // Middle transparent ring<br>        canvas.drawOval(<br>            RectF(<br>                x + whiteOffset,<br>                y + whiteOffset,<br>                x + whiteOffset + whiteDiameter,<br>                y + whiteOffset + whiteDiameter<br>            ),<br>            clearPaint<br>        )<br><br>        // Inner black dot<br>        paint.color = qrColor<br>        canvas.drawOval(<br>            RectF(<br>                x + middleOffset,<br>                y + middleOffset,<br>                x + middleOffset + middleDiameter,<br>                y + middleOffset + middleDiameter<br>            ),<br>            paint<br>        )<br>    }<br><br>    /**<br>     * Decodes a bitmap from a URI, supporting both modern and legacy Android versions.<br>     *<br>     * @param context The Android context used for resource access.<br>     * @param uri The URI of the image to decode.<br>     * @return A mutable Bitmap decoded from the URI.<br>     */<br>    private fun decodeBackgroundBitmap(context: Context, uri: Uri): Bitmap {<br>        return if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.P) {<br>            val source = ImageDecoder.createSource(context.contentResolver, uri)<br>            ImageDecoder.decodeBitmap(source) { decoder, _, _ -&gt;<br>                decoder.isMutableRequired = true<br>                decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE<br>                decoder.setTargetColorSpace(ColorSpace.get(ColorSpace.Named.SRGB))<br>            }<br>        } else {<br>            @Suppress(&quot;DEPRECATION&quot;)<br>            MediaStore.Images.Media.getBitmap(context.contentResolver, uri)<br>        }<br>    }<br><br>    /**<br>     * Overlays a QR code bitmap on top of a background bitmap.<br>     *<br>     * @param qrBitmap The QR code bitmap.<br>     * @param backgroundBitmap The background bitmap.<br>     * @return A new Bitmap with the QR code overlaid on the background.<br>     */<br>    private fun overlayBackground(qrBitmap: Bitmap, backgroundBitmap: Bitmap): Bitmap {<br>        val output = createBitmap(qrBitmap.width, qrBitmap.height)<br>        val canvas = Canvas(output)<br>        val scaledBackground =<br>            backgroundBitmap.scale(qrBitmap.width, qrBitmap.height)<br>        canvas.drawBitmap(scaledBackground, 0f, 0f, null)<br>        canvas.drawBitmap(qrBitmap, 0f, 0f, null)<br>        return output<br>    }<br><br>    /**<br>     * Generates a QR code bitmap asynchronously based on the provided configuration.<br>     *<br>     * @param config The configuration for the QR code, including size, color, and visual style.<br>     * @return A QrImageResult containing the generated QR code or an error.<br>     */<br>    override suspend fun generateQrBitmap(config: QrStyleConfig): QrImageResult {<br>        val bitmap = generateQrCode(config) ?: return QrImageResult.Error<br>        return QrImageResult.Android(bitmap.asImageBitmap())<br>    }<br>}</pre><h3>Usage</h3><p>Initialize:</p><pre>val generator = QrCodeGeneratorImpl(context</pre><p>Configure:</p><pre>val config = QrStyleConfig(<br>    preparedText = &quot;https://example.com&quot;,<br>    width = 512,<br>    height = 512,<br>    qrColor = Color.BLACK,<br>    qrVisualCategory = QrVisualCategory.ROUNDED_DOTS,<br>    logoUri = &quot;content://path/to/logo.png&quot;,<br>    backgroundUri = null<br>)</pre><p>Generate QR Code:</p><pre>coroutineScope.launch {<br>    when (val result = generator.generateQrBitmap(config)) {<br>        is QrImageResult.Android -&gt; {<br>            Image(bitmap = result.bitmap, contentDescription = &quot;QR Code&quot;)<br>        }<br>        is QrImageResult.Error -&gt; {<br>            // Handle error<br>        }<br>    }<br>}</pre><h3>Considerations</h3><ul><li>Ensure valid URIs for <strong>logoUri</strong> and <strong>backgroundUri</strong>.</li><li>Use a coroutine scope to <strong>generateQrBitmap</strong>.</li><li>Test scannability with stylized patterns or logos.</li><li>Handle <strong>QrImageResult.Error</strong> for empty text or decoding failures.</li></ul><h3>Dependencies</h3><ul><li>ZXing: <em>c</em><strong><em>om.google.zxing:core</em></strong></li><li>Jetpack Compose: <strong><em>androidx.compose.ui:ui-graphics</em></strong></li><li>Android graphics: <strong><em>android.graphics.*</em></strong></li></ul><h3>Source Code</h3><p>The full implementation is available on <strong>GitHub</strong>: <a href="https://github.com/Nishikanto/QrCodeGeneratorKMP">https://github.com/Nishikanto/QrCodeGeneratorKMP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0adb06757d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My 10-Year Journey as an Android Developer]]></title>
            <link>https://medium.com/@nishikanto.abm/my-10-year-journey-as-an-android-developer-2294515f7c04?source=rss-b3f9e482bf1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2294515f7c04</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[mobile-application]]></category>
            <category><![CDATA[ai-ml-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[carrier]]></category>
            <dc:creator><![CDATA[Nishikanto Sarkar]]></dc:creator>
            <pubDate>Fri, 16 May 2025 04:39:02 GMT</pubDate>
            <atom:updated>2025-05-16T04:39:02.780Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KO5xE__tM-nmhaASwOS8FQ.jpeg" /></figure><p>During my undergraduate studies, I built my first application for the Android platform and even earned money from it. That was my first income, so it was an emotional moment for me. I felt proud. Since that day, ten years have passed, and I am still developing Android applications for a living.</p><p>Long before starting my graduation, I loved this small device called a phone. From my Nokia 3310 to my current Samsung Galaxy S23, I have used so many different phones. I always wondered how these devices work, why they function the way they do, and what more they could be capable of. Somehow, this curiosity and passion became my profession. Throughout my journey with Android, I have built countless apps. Some were published, while others remained unfinished, sitting idle in my GitHub account or on my computer’s hard drive. I am quite certain more will be added to that list in the future.</p><p>The technology behind Android app development has changed a lot over time. Some good features became deprecated, and new, better ones took their place. However, my passion for Android has never changed. To be honest, I have considered switching to a different career path from time to time, but I always return to the decision to stay connected with the Android world. That said, I am confident I can adapt to anything if life demands.</p><p>I have heard many times that backend development is considered superior to frontend or mobile development. You can build anything there — big systems like handling data for millions of users, maintaining servers for high-traffic moments, or working with AI and machine learning. I completely agree with that. Additionally, backend development can offer faster career growth. In comparison, mobile development has limited resources, which might seem to restrict its scope. However, if you accept these limitations, a different door opens for you: the user, the mighty user. You will be directly building for them. You will be responsible for improving their experience. Everything we, as mobile developers, do is solely for the user. And there are countless ways you can impress the user through your work. What about AI and Machine learning? With tools like TensorFlow Lite and the rise of edge computing, we developers can actually build and research AI models that run directly on mobile devices. This whole area of mobile AI is still growing, and there’s a lot to explore. Contributing here means solving real-life problems while dealing with the unique limitations of mobile platforms.</p><p>Every platform in software engineering has its own pros and cons. One may give you the satisfaction of working on complex systems, while another allows you to showcase your creativity. What matters most is what you enjoy. The more you enjoy something, the better you will become at it. Hence, do what you love, but also sharpen your adaptability by learning new things from time to time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2294515f7c04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Data binding]]></title>
            <link>https://medium.com/infancyit/android-data-binding-42077de5f7c9?source=rss-b3f9e482bf1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/42077de5f7c9</guid>
            <category><![CDATA[data-binding]]></category>
            <category><![CDATA[android-ui]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-data-binding]]></category>
            <category><![CDATA[android-application]]></category>
            <dc:creator><![CDATA[Nishikanto Sarkar]]></dc:creator>
            <pubDate>Wed, 28 Feb 2018 16:53:07 GMT</pubDate>
            <atom:updated>2018-03-02T14:13:13.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pgFREsmroqa52ITl4iBPZQ.png" /><figcaption>photo taken from www.<a href="https://mobikul.com/data-binding-technique-android/">mobikul.com</a></figcaption></figure><p><strong>Initiating data binding</strong></p><p>I have recently learned android data binding. After learning it, I realized that I should have learned it earlier. You know why? Because using data binding can make your code more readable, less coding and also smart looking. I also found out that the documentation of android data binding is not so understandable. So I thought, I should write a short story about how to get started with android data binding.</p><p>Recently I’ve made an android app where I had to use 25 fields in one activity. I know this is not a good approach for UI design. But for some reason, I had to do that. So here come all the findViewbyIds, And it’s really a pain that why I should write so many unnecessary findViewByIds. Here I could use Butterknife instead of using findViewByIds but that’s not enough. Because I still have to identify the elements by using their ids on the XML.</p><p>No more talking. let’s get started with the basics of data binding. I will assume that you already know the basics android development. So I will go straight to data binding. In this story, we will make a login view using data binding. <br>First, we need to enable the data binding in app-level build.gradle. Add this block of code to build.gradle and your application is ready to use data binding.</p><pre>dataBinding {<br>    enabled = true<br>}</pre><p>now we will create our view.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;layout&gt;<br><br>    &lt;data&gt;<br><br>    &lt;/data&gt;<br><br>    &lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>        xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:gravity=&quot;center&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        tools:context=&quot;com.infancyit.newtestproject.main_activity.MainActivity&quot;&gt;<br><br>        &lt;LinearLayout<br>            android:gravity=&quot;center&quot;<br>            android:orientation=&quot;vertical&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;&gt;<br><br>            &lt;EditText<br>                android:layout_marginBottom=&quot;20dp&quot;<br>                android:hint=&quot;User Name&quot;<br>                android:layout_width=&quot;150dp&quot;<br>                android:layout_height=&quot;wrap_content&quot; /&gt;<br><br>            &lt;EditText<br>                android:layout_marginBottom=&quot;20dp&quot;<br>                android:hint=&quot;password&quot;<br>                android:layout_width=&quot;150dp&quot;<br>                android:layout_height=&quot;wrap_content&quot; /&gt;<br><br>            &lt;Button<br>                android:layout_marginTop=&quot;20dp&quot;<br>                android:text=&quot;Login&quot;<br>                android:layout_width=&quot;wrap_content&quot;<br>                android:layout_height=&quot;wrap_content&quot; /&gt;<br><br>        &lt;/LinearLayout&gt;<br><br>    &lt;/LinearLayout&gt;<br><br>&lt;/layout&gt;</pre><p>In our login view, we just have three fields. two Edittext and one Button. we will give no id here. because we won’t need any ids. Well, you probably thinking where did the &lt;layout&gt; and &lt;data&gt; tag come from? These two tags will allow you to bind your views with the java code.</p><p>Now we have to create a java class which is called the view model. You can name it LoginViewModel. Now lets put some code in the &lt;data&gt; tag.</p><pre>&lt;data&gt;<br>    &lt;variable<br>        name=&quot;loginViewModel&quot;<br>          type=&quot;com.infancyit.newtestproject.main_activity.LoginViewModel&quot;/&gt;<br>&lt;/data&gt;</pre><p>Now you can see there is a new tag called variable. Well, this LoginViewModel class will bind with our view. so it’s like a variable for this view. We will go details about &lt;data&gt; tag in another chapter. our variable tag has two fields called name and type. In the name field, we can use any name. But, it’s better to use the class name with the 1st letter in lowercase like a variable naming conventions. And, in the type field, we have to give the location of the class.</p><p>After that, lets put some codes in our MainActvity’s onCreate() method. this few line will initiate your view and binding class.</p><pre>@Override<br>protected void onCreate(Bundle savedInstanceState) {<br>    super.onCreate(savedInstanceState);<br><br>    ActivityMainBinding binding = DataBindingUtil.<em>setContentView</em>(this, <br>            R.layout.<em>activity_main</em>);<br>    <br>    LoginViewModel loginViewModel = new LoginViewModel();<br>    binding.setLoginViewModel(loginViewModel);<br><br>}</pre><p>In data binding, we will set our content view with a different style. In the above code block, you can see there is a new class called “ActivityMainBinding”. This class is auto-generated from the “activity_main.xml”. This class only gets generated when you use the &lt;layout&gt; tag as a parent of your layout.</p><pre>ActivityMainBinding binding = DataBindingUtil.<em>setContentView</em>(this, <br>            R.layout.<em>activity_main</em>);</pre><p>This line will set the content view to the main activity class. And we get a binding instance. which will use to set the variable that we put in the &lt;data&gt; tag in our main_activity.xml layout.</p><pre>LoginViewModel loginViewModel = new LoginViewModel();<br>    binding.setLoginViewModel(loginViewModel);</pre><p>Our binding instance has an auto-generated method called setLoginViewModel(). So first we create an instance of our class LoginViewModel. Then, pass this instance to the parameter of setLoginViewModel() method.</p><p>Now we will see how to use those fields in our view without using findViewByIds.</p><h4><strong>Using data binding</strong></h4><p>At first lets declare two variable in the LoginViewModel class.</p><pre>public class LoginViewModel {<br>    <br>    private String name;<br>    private String password;<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public String getPassword() {<br>        return password;<br>    }<br><br>    public void setPassword(String password) {<br>        this.password = password;<br>    }<br>}</pre><p>We need this getter setter method for accessing this variable from the layout. And now the fun part will begin. We are gonna bind this two variable with our views.</p><pre>&lt;EditText<br>    android:layout_marginBottom=&quot;20dp&quot;<br>    android:hint=&quot;User Name&quot;<br>    <strong>android:text=&quot;@{loginViewModel.name}&quot;</strong><br>    android:layout_width=&quot;150dp&quot;<br>    android:layout_height=&quot;wrap_content&quot; /&gt;<br><br>&lt;EditText<br>    android:layout_marginBottom=&quot;20dp&quot;<br>    android:hint=&quot;password&quot;<br>    <strong>android:text=&quot;@{loginViewModel.password}&quot;</strong><br>    android:layout_width=&quot;150dp&quot;<br>    android:layout_height=&quot;wrap_content&quot; /&gt;</pre><p>This two bold line will do the magic of data binding. when (name and password) those variable gets the value the views will immediately get that value too. We don’t have to set directly set anything to the view. We just have to set data to the model and our views will get those values from the model directly.</p><p>Here we have two EditText. So we need two-way binding. But first, let me tell about this one-way binding and two-way binding.</p><h4>One way binding</h4><p>One way binding means our views will get value from our model’s variable. For example, we have a TextView. Now TextView is not an input field. We just set a text to the TextView. So this just one way binding with models.</p><pre>&lt;TextView<br>    android:text=&quot;@{loginViewModel.name}&quot;<br>    android:layout_width=&quot;wrap_content&quot;<br>    android:layout_height=&quot;wrap_content&quot; /&gt;</pre><p>So all the views or fields those are not input fileds will use one way binding.</p><h4>Two way binding</h4><p>In EditText The view gets data from the user or from the model. Because it’s an input field so we will need two-way binding here. When user type anything in the EditText our model’s variable immediately gets those text. Like we don’t have to get the text with getText() method. isn’t it cool? So for two way binding, we have just added an equal sign(=) after the @ sign.</p><pre>&lt;EditText<br>    android:layout_marginBottom=&quot;20dp&quot;<br>    android:hint=&quot;User Name&quot;<br>    <strong>android:text=&quot;@={loginViewModel.name}&quot;</strong><br>    android:layout_width=&quot;150dp&quot;<br>    android:layout_height=&quot;wrap_content&quot; /&gt;<br><br>&lt;EditText<br>    android:layout_marginBottom=&quot;20dp&quot;<br>    android:hint=&quot;password&quot;<br>    <strong>android:text=&quot;@={loginViewModel.password}&quot;</strong><br>    android:layout_width=&quot;150dp&quot;<br>    android:layout_height=&quot;wrap_content&quot; /&gt;</pre><p>and also we will see the other features that binding provides us. So our fields are ready to use. But there is one problem. In our LoginViewModel class, we declare two fields as string type. But in two binding we need to us a new type of fields called observable. And also initialize those fields in the constructor.</p><pre>public class LoginViewModel {<br><br>    private ObservableField&lt;String&gt; name;<br>    private ObservableField&lt;String&gt; password;<br><br>    public void onLoginButtonClick(){<br>        name = new ObservableField&lt;&gt;();<br>        password = new ObservableField&lt;&gt;();<br>    }<br><br>    public ObservableField&lt;String&gt; getName() {<br>        return name;<br>    }<br><br>    public ObservableField&lt;String&gt; getPassword() {<br>        return password;<br>    }<br><br>    public void setName(ObservableField&lt;String&gt; name) {<br>        this.name = name;<br>    }<br><br>    public void setPassword(ObservableField&lt;String&gt; password) {<br>        this.password = password;<br>    }<br>}</pre><p>Now we are good to go.</p><h4>Setting on click listener</h4><p>Now we have to set on click listener to our login button. Like above we will use data binding for our button too. So we don’t need any id for our button too. just have to add one line to the button views.</p><pre>&lt;Button<br>    android:layout_marginTop=&quot;20dp&quot;<br>    android:text=&quot;Login&quot;<br><strong>    android:onClick=&quot;@{()-&gt;loginViewModel.onLoginButtonClick()}&quot;<br></strong>    android:layout_width=&quot;wrap_content&quot;<br>    android:layout_height=&quot;wrap_content&quot; /&gt;</pre><p>And create a method named onLoginButtonClick() in the LoginViewModel Class. That’s all. our data binding is complete.</p><pre>public void onLoginButtonClick(){<br><br>}</pre><p>Here we use LoginViewModel class for everything. but if you want you can create another class for setting the click listener to the button or making the HTTP request. It’s your choice. You just have to add another variable to your layout. and also set the class in onCreate() in the activity class.</p><p>There is a lot more in data binding. I will suggest you look android developer documentation and find more feature of data binding. In future, I will try to write about Listview Data binding. Thank you for reading my story. If you like don’t forget to clap.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42077de5f7c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/infancyit/android-data-binding-42077de5f7c9">Android Data binding</a> was originally published in <a href="https://medium.com/infancyit">InfancyIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>