<?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 WhiteBatCodes on Medium]]></title>
        <description><![CDATA[Stories by WhiteBatCodes on Medium]]></description>
        <link>https://medium.com/@WhiteBatCodes?source=rss-fc7b5f06c16c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ut69wpOhDhpJOgfrnSYUbg.png</url>
            <title>Stories by WhiteBatCodes on Medium</title>
            <link>https://medium.com/@WhiteBatCodes?source=rss-fc7b5f06c16c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 18:09:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@WhiteBatCodes/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[How ChatGPT Propelled a Software Engineer to Success: A Journey of Innovation and Promotion]]></title>
            <link>https://medium.com/@WhiteBatCodes/how-chatgpt-propelled-a-software-engineer-to-success-a-journey-of-innovation-and-promotion-6c5d118356c2?source=rss-fc7b5f06c16c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c5d118356c2</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[WhiteBatCodes]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 11:31:10 GMT</pubDate>
            <atom:updated>2023-06-19T11:31:10.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EWgafZUQfpFXv-rq-l4PA.jpeg" /></figure><h3>Introduction</h3><p>In the fast-paced world of software engineering, staying ahead of the curve is crucial for professional growth. Embracing new technologies and tools can be a game-changer, and one such tool that has revolutionized the industry is ChatGPT. In this article, we delve into the inspiring story of Sarah, a software engineer who harnessed the power of ChatGPT to excel at her job and achieve a well-deserved promotion. Join us as we explore how ChatGPT transformed Sarah’s career and became a catalyst for innovation within her team.</p><h3>The Quest for Productivity:</h3><p>Sarah, a talented software engineer, was determined to enhance her skills and productivity. She recognized the potential of ChatGPT and decided to integrate it into her Integrated Development Environment (IDE). By doing so, she gained a powerful coding companion that would revolutionize her workflow.</p><h3>Conquering Complex Challenges:</h3><p>During a critical project, Sarah encountered a perplexing bug that had her stumped. Instead of spending hours scouring documentation and forums, she turned to ChatGPT for assistance. By providing the relevant code snippet and describing the issue in natural language, Sarah tapped into ChatGPT’s capabilities. The AI-powered model quickly analyzed the code, identified potential causes, and suggested a solution. The solutions suggested weren’t always working and sometimes ChatGPT failed to assist her in finding the solutions, but the investigative part of ChatGPT was a great advantage she didn’t hesitate to use.</p><h3>Boosting Efficiency and Innovation</h3><p>Buoyed by her initial success, Sarah continued to leverage ChatGPT in her day-to-day work. She discovered that ChatGPT could generate code snippets for repetitive tasks, saving her valuable time and boosting her productivity. Additionally, Sarah found that ChatGPT’s natural language processing capabilities made it an invaluable resource for seeking documentation, clarifying complex concepts, and exploring alternative solutions. As she integrated ChatGPT into her workflow, Sarah’s efficiency soared, and her innovative approach caught the attention of her colleagues.</p><p>Sarah’s utilization of ChatGPT enabled her to create rapid proof-of-concepts (POCs) and demos, accelerating her development process. Moreover, she effectively bridged knowledge gaps in areas where she had limited or no prior expertise. Rather than investing excessive time in comprehensive learning, Sarah strategically focused on acquiring the necessary foundational knowledge directly relevant to her project. This approach allowed her to grasp the basics associated with the project and determine the optimal methods for implementation. By leveraging ChatGPT’s assistance, Sarah optimized her learning process and efficiently applied her newfound knowledge to her ongoing projects.</p><h3>Spreading the ChatGPT Revolution:</h3><p>Impressed by the positive impact Sarah had on the team’s productivity, her manager decided to adopt ChatGPT as a collaborative coding tool for the entire team. As ChatGPT became an integral part of their workflow, the team experienced improved code quality, faster debugging, and enhanced knowledge sharing. Sarah’s contributions were recognized, and she was promoted to a senior software engineer role, entrusted with leading critical projects and mentoring junior developers.</p><p>With the skills Sarah acquired and the methods she employed, she was able to focus her learning efforts on the specific skills required for the project. This approach not only saved her time but also provided her with invaluable experience. Sarah asked insightful questions such as, “What investigative approach should be taken to resolve this issue?” and “Why is networking included in the investigative plan when the error is related to database persistence?” By harnessing the power of AI for analysis and adapting it to her own needs, Sarah empowered her professional experience with the assistance of AI.</p><h3>Conclusion</h3><p>Sarah’s journey exemplifies the transformative power of ChatGPT in the realm of software engineering. By embracing this AI-powered language model, Sarah not only enhanced her skills and productivity but also became a catalyst for innovation within her team. As software engineers, let us be inspired by Sarah’s story and embrace the potential of ChatGPT to unlock new levels of productivity, efficiency, and innovation in our own careers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c5d118356c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java | Exploring Methods to Implement the Prototype Pattern]]></title>
            <link>https://medium.com/@WhiteBatCodes/java-exploring-methods-to-implement-the-prototype-pattern-b9a99472e0de?source=rss-fc7b5f06c16c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9a99472e0de</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[WhiteBatCodes]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 20:38:14 GMT</pubDate>
            <atom:updated>2023-06-12T20:38:14.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AnjWQFgnc4_1WujwHHbtAg.png" /></figure><h4>Introduction:</h4><p>The Prototype pattern provides a mechanism for creating duplicate objects, or prototypes, by cloning existing objects. Java offers several methods to implement the Prototype pattern, each with its own advantages and use cases. In this article, we will explore three commonly used methods to implement the Prototype pattern in Java. We will discuss each method in detail, provide code examples, and highlight their benefits and considerations.</p><h4>Method 1: Implementing Cloneable Interface:</h4><p>The simplest method to implement the Prototype pattern in Java is by using the Cloneable interface provided by the language. The steps to implement this method are as follows:</p><p>a. Implement the Cloneable interface in the class you want to make cloneable. b. Override the clone() method inherited from the Object class and provide the necessary logic to create a copy of the object. c. Use the clone() method to create clones of the object as needed.</p><p>Example:</p><pre>public class MyClass implements Cloneable {<br>    private int data;<br><br>    // Constructor, getters, and setters...<br><br>    @Override<br>    public Object clone() throws CloneNotSupportedException {<br>        return super.clone();<br>    }<br>}</pre><p>The Cloneable interface acts as a marker interface that indicates an object&#39;s ability to be cloned. By implementing Cloneable and overriding the clone() method, we enable the creation of shallow copies of the object.</p><h4>Method 2: Implementing the Prototype Interface:</h4><p>The second method involves defining a prototype interface that declares a clone() method, which each concrete class implementing the prototype will override. This method allows for a common interface for all prototype classes. The steps to implement this method are as follows:</p><p>a. Create a prototype interface with a clone() method. b. Implement the prototype interface in the concrete classes that need to be cloned. c. Provide the necessary logic to create a copy of the object in the clone() method of each concrete class.</p><p>Example:</p><pre>public interface Prototype {<br>    Prototype clone();<br>}<br><br>public class MyClass implements Prototype {<br>    private int data;<br><br>    // Constructor, getters, and setters...<br><br>    @Override<br>    public Prototype clone() {<br>        return new MyClass(data);<br>    }<br>}</pre><p>In this approach, the Prototype interface defines the clone() method that each concrete class implements. This method allows for greater control over the cloning process and supports polymorphism.</p><h4>Method 3: Using Serialization:</h4><p>The third method to implement the Prototype pattern involves serialization. By serializing and deserializing the object, a deep copy can be created. The steps to implement this method are as follows:</p><p>a. Implement the Serializable interface in the class you want to make cloneable. b. Serialize the object to a byte stream. c. Deserialize the byte stream to create a deep copy of the object.</p><p>Example:</p><pre>import java.io.*;<br><br>public class MyClass implements Serializable {<br>    private int data;<br><br>    // Constructor, getters, and setters...<br><br>    public MyClass deepCopy() throws IOException, ClassNotFoundException {<br>        ByteArrayOutputStream baos = new ByteArrayOutputStream();<br>        ObjectOutputStream oos = new ObjectOutputStream(baos);<br>        oos.writeObject(this);<br><br>        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());<br>        ObjectInputStream ois = new ObjectInputStream(bais);<br>        return (MyClass) ois.readObject();<br>    }<br>}</pre><p>By implementing the Serializable interface, the object can be serialized and deserialized to create a deep copy. This method provides flexibility and control over the cloning process, especially when dealing with complex objects.</p><h4>Conclusion:</h4><p>The Prototype pattern allows for the creation of duplicate objects by cloning existing ones. In Java, there are multiple methods to implement the Prototype pattern, each with its own benefits and considerations. The choice of method depends on factors such as the complexity of the object being cloned, the desired level of control over the cloning process, and performance considerations. By understanding and utilizing these methods, developers can effectively implement the Prototype pattern in their applications and achieve efficient object duplication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9a99472e0de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java | Simplifying User Object Construction with the Builder Pattern]]></title>
            <link>https://medium.com/@WhiteBatCodes/java-simplifying-user-object-construction-with-the-builder-pattern-e808c114e866?source=rss-fc7b5f06c16c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e808c114e866</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[WhiteBatCodes]]></dc:creator>
            <pubDate>Sat, 10 Jun 2023 20:40:45 GMT</pubDate>
            <atom:updated>2023-06-10T21:35:15.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FL9QlpTBGtY-113LF2i_6w.png" /></figure><h4>Introduction</h4><p>Creating objects with multiple attributes, including optional ones, can be a complex task in software development. The Fluent Builder pattern offers an elegant solution by providing a fluent and expressive API for constructing objects. In this article, we will explore the Fluent Builder pattern in the context of building a Lunch object. We will demonstrate its benefits, provide a practical example, and discuss use cases where this pattern can be applied.</p><h4>Understanding the Lunch Class:</h4><p>Let’s consider the Lunch class, which represents a meal with attributes such as entree, mainDish, dessert, drink, bread, and sideDish. We want to construct a Lunch object with these attributes while allowing some of them to be optional.</p><pre>public class Lunch {<br>    private String entree;<br>    private String mainDish;<br>    private String dessert;<br>    private String drink;<br>    private String bread;<br>    private String sideDish;<br><br>    // Constructors and getters...<br>}</pre><h4>The Fluent Builder Pattern:</h4><p>The Fluent Builder pattern provides a flexible and readable way to construct objects. It involves defining a builder class that contains setter methods for each attribute, allowing method chaining to create a fluent and expressive syntax. Let’s see how the Fluent Builder pattern can be implemented for the Lunch class:</p><pre>public class Lunch {<br>    private String entree;<br>    private String mainDish;<br>    private String dessert;<br>    private String drink;<br>    private String bread;<br>    private String sideDish;<br><br>    private Lunch() {<br>        // Private constructor to enforce building through the builder<br>    }<br><br>    public static class Builder {<br>        private String entree;<br>        private String mainDish;<br>        private String dessert;<br>        private String drink;<br>        private String bread;<br>        private String sideDish;<br><br>        public Builder() {<br>            // Initialize optional attributes with default values or null<br>            this.drink = &quot;Water&quot;;<br>            this.bread = &quot;None&quot;;<br>            this.sideDish = &quot;None&quot;;<br>        }<br><br>        public Builder withEntree(String entree) {<br>            this.entree = entree;<br>            return this;<br>        }<br><br>        public Builder withMainDish(String mainDish) {<br>            this.mainDish = mainDish;<br>            return this;<br>        }<br><br>        public Builder withDessert(String dessert) {<br>            this.dessert = dessert;<br>            return this;<br>        }<br><br>        public Builder withDrink(String drink) {<br>            this.drink = drink;<br>            return this;<br>        }<br><br>        public Builder withBread(String bread) {<br>            this.bread = bread;<br>            return this;<br>        }<br><br>        public Builder withSideDish(String sideDish) {<br>            this.sideDish = sideDish;<br>            return this;<br>        }<br><br>        public Lunch build() {<br>            Lunch lunch = new Lunch();<br>            lunch.entree = this.entree;<br>            lunch.mainDish = this.mainDish;<br>            lunch.dessert = this.dessert;<br>            lunch.drink = this.drink;<br>            lunch.bread = this.bread;<br>            lunch.sideDish = this.sideDish;<br>            return lunch;<br>        }<br>    }<br><br>    // Getters for attributes...<br>}</pre><p>In this example, we have a nested Builder class within the Lunch class. The Builder class contains setter methods for each attribute, allowing fluent method chaining. The build() method constructs the Lunch object by assigning the attribute values from the builder to the new Lunch instance.</p><h4>Building a Lunch Object with the Fluent Builder:</h4><p>Using the Fluent Builder pattern, constructing a Lunch object becomes intuitive and customizable. Let&#39;s create a Lunch object with specific attributes:</p><pre>Lunch lunch = new Lunch.Builder()<br>        .withEntree(&quot;Salad&quot;)<br>        .withMainDish(&quot;Steak&quot;)<br>        .withDessert(&quot;Ice Cream&quot;)<br>        .withDrink(&quot;Soda&quot;)<br>        .withBread(&quot;Garlic bread&quot;)<br>        .withSideDish(&quot;Mashed potatoes&quot;)<br>        .build();</pre><p>With the Fluent Builder pattern, we can easily set the desired attributes in a single chained sequence of method calls. Optional attributes can be omitted, and they will be assigned default values specified within the builder class.</p><h4>Benefits of the Fluent Builder Pattern:</h4><p>The Fluent Builder pattern offers several advantages:</p><p><strong>a. Readability and Expressiveness: </strong>The fluent method chaining syntax provides a clear and readable way to construct objects. Each method call represents an attribute assignment, making the code self-explanatory.</p><p><strong>b. Customization and Flexibility: </strong>The pattern allows for selective attribute setting, making it easy to construct objects with different combinations of attributes. Optional attributes can be conveniently omitted or specified as needed.</p><p><strong>c. Encapsulation and Separation of Concerns: </strong>The construction logic is encapsulated within the builder class, separating it from the main class. This promotes a clean and organized code structure.</p><p><strong>d. Improved Maintainability: </strong>With the Fluent Builder pattern, adding new attributes or modifying the construction process does not affect the client code. This makes the codebase more maintainable and less prone to errors.</p><h4>Use Cases for the Fluent Builder Pattern:</h4><p>The Fluent Builder pattern is beneficial in various scenarios, including:</p><p><strong>a. Configurable Object Creation: </strong>When constructing objects with many attributes, some of which are optional or have default values, the Fluent Builder pattern simplifies the configuration process. It provides a concise and flexible way to create objects with different attribute combinations.</p><p><strong>b. API Design:</strong> The Fluent Builder pattern is commonly used in API design to provide a user-friendly and expressive interface for constructing complex objects. It enhances the usability of the API and allows users to specify attributes in a readable and intuitive manner.</p><p><strong>c. Test Data Builders:</strong> When writing tests, the Fluent Builder pattern can be used to construct test data objects with specific attribute values. This makes tests more readable and maintainable, allowing developers to focus on the essential aspects of the test cases.</p><h4>Conclusion:</h4><p>The Fluent Builder pattern offers a powerful and elegant approach to construct objects with multiple attributes, including optional ones. It improves code readability, flexibility, and maintainability. By providing a fluent and expressive API, it simplifies the process of object creation and customization. When faced with complex object construction scenarios, consider leveraging the Fluent Builder pattern to enhance your codebase and improve the overall development experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e808c114e866" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[YOU MUST KNOW THESE TYPES OF SINGLETON DESIGN PATTERNS IMPLEMENTATIONS]]></title>
            <link>https://medium.com/@WhiteBatCodes/you-must-know-these-types-of-singleton-design-patterns-implementations-2840385fd550?source=rss-fc7b5f06c16c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2840385fd550</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[WhiteBatCodes]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 17:30:43 GMT</pubDate>
            <atom:updated>2023-06-10T20:40:19.263Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5g8Z0Y_54KjHuX5yDam9qA.png" /></figure><p>In Java, a singleton is a design pattern that ensures a class has only one instance, providing global access to that instance. Singletons are commonly used in scenarios where having multiple instances could lead to inconsistent or undesirable behavior. In this article, we will explore the concepts of lazy loading and eager loading in singletons, along with examples of thread-safe implementations.</p><h3>Lazy loading approach</h3><p>The lazy loading approach refers to the fact that you only load the singleton when you need it. In other words, you only initiate the instance when calling <strong><em>getInstance(). </em></strong>So, even if you have other static methods in your Singleton class that will load a configuration, for example, and those methods are used to start up your application, the initialization process is only limited to the getInstance() method. This way, your application start time will not be impacted by the loading time of the instance. This is why we call it the “lazy approach”.</p><h4>Lazy loading in a classic Singleton</h4><p>The lazy loading approach is commonly used in the classic singleton. Let’s first explore the classic singleton class that used in a single threaded application.</p><p>It’s a simple class that can be implemented where we have a private constructor, and we can call the <strong><em>getInstance() </em></strong>to initialize the variable if it was still null. The result should look like this:</p><pre>public class Singleton {<br><br>    private static Singleton instance;<br><br>    private Singleton() {<br>    }<br><br>    public static Singleton getInstance() {<br>        if(instance == null){<br>            instance = new Singleton();<br>        }<br>        return instance;<br>    }<br>}</pre><p>This is a good approach to follow if you have a single thread running in your entire context. It’s not the case for most of the application, as most applications use multi threading. So what’s left to do is to perform some synchronization on your singleton.</p><h4>Synchronized Lazy loading</h4><p>Synchronization can be tricky as there are two approaches we can use here:</p><ul><li>Synchronize the entire <strong><em>getInstance()</em></strong> method</li><li>Synchronize part of the method</li></ul><p>Let’s implement the following java code:</p><pre>public class ThreadSafeSingleton {<br><br>    private static ThreadSafeSingleton instance;<br><br>    private ThreadSafeSingleton() {<br>    }<br><br>    public static synchronized ThreadSafeSingleton getInstance() {<br>        if(instance == null){<br>            Main.waitTime();<br>            Main.waitTime();<br>            instance = new ThreadSafeSingleton();<br>        }<br>        Main.waitTime();<br>        return instance;<br>    }<br><br>    public static ThreadSafeSingleton getInstanceOptimized() {<br>        if(instance == null){<br>            synchronized (ThreadSafeSingleton.class){<br>                if(instance == null){<br>                    Main.waitTime();<br>                    Main.waitTime();<br>                    instance = new ThreadSafeSingleton();<br>                }<br>            }<br>        }<br>        Main.waitTime();<br>        return instance;<br>    }<br>}</pre><p>In the first method : <strong><em>getInstance()</em></strong> is synchronized, and this means it can be called by a single thread at a time.</p><p>The second method : <strong><em>getInstanceOptimized()</em></strong> is also synced, but the sync is focused on the initialization process of the variable. We have added 2 null checks as the threads will be blocked after entering the first null check, and we have to make sure that the other threads don’t reset the value, again after it was initialized.</p><p>The main difference here is that, by adding the waitTime(), that is basically just a <strong><em>Thread.sleep()</em></strong><em> </em>method, and calling the <strong><em>getInstance </em></strong>inside multiple threads, you’ll find that the values printed by the threads take time during the initialization process and also during the return process as they are blocked from running the method to allow a single thread to run it at a time.</p><p>For the second method, we’re only syncing the initialization process as it’s the core step of the singleton, and it could risk us having multiple instances if not synced.</p><p>Now, what’s the difference, you might think. The wait before returning the result symbolizes operations that run after the initialization process. The question you should ask yourself is: Are the operations pre-return essential? Do they impact the instance or change its state or its core variables? Is the change to the instance is going to reflect negatively on the operations that will be performed on the instance?</p><p>If the response is YES, then syncing the method is the way to go, if not, then you can limit the synchronization process to the initialization only.</p><p>Now the result is 100% thread safe! But what about using the native Java syncing in creating the instance?</p><p>That would be a great approach to follow, and it’s called On demand Holder.</p><h4>Initialization-on-demand Holder</h4><p>The initialization On demand holder is still part of the Lazy initialization. We’ll explain this right after the code:</p><pre>public class OnDemandSingleton {<br>    private OnDemandSingleton() {<br>    }<br><br>    private static class SingletonHolder{<br>        private static final OnDemandSingleton instance = new OnDemandSingleton();<br>    }<br><br>    public static OnDemandSingleton getInstance(){<br>        return SingletonHolder.instance;<br>    }<br>}</pre><p>Notice here that we have a static inner class that contains a static variable. We know that static variables&#39; initialization is called when the class is loaded. In our context, the loading is performed when we call <strong><em>getInstance()</em></strong>. So we’re still in the lazy initialization process.</p><p>From a thread safety process, Java ensure that natively by syncing the initialization of the instance in the inner class.</p><p>This method is similar to the last approach we have implemented, which is the thread safe implementation with “getInstanceOptimized()”.</p><h3>Eager loading approach</h3><p>The eager loading approach refers to the fact that you load the singleton when your Singleton class is loaded instead of when you need it. In other words, you only initiate the instance in the class variable, and you return it in <strong><em>getInstance(). </em></strong>So, if you have other static methods in your Singleton class that will load a configuration, for example, and those methods are used to start up your application, the initialization process is going to be called and thus, impacting your application startup time. This is why we call it the “eager approach”.</p><p>The code for the eager loading of the singleton is the following:</p><pre>public class EagerSingleton {<br>    private static final EagerSingleton instance = new EagerSingleton();<br><br>    private EagerSingleton() {<br>        Main.waitTime();<br>        Main.waitTime();<br>    }<br><br>    public static EagerSingleton getInstance() {<br>        Main.waitTime();<br>        return instance;<br>    }<br>}</pre><p>Now let’s see the difference between the two calls in a main method.</p><p>Let’s pick the <strong><em>EagerSingleton </em></strong>and the <strong><em>ThreadSafeSingleton </em></strong>classes. For the last class, we’ll use the optimized method.</p><p>Our main should look like this:</p><pre>package com.whitebatcodes.singleton;<br><br>public class Main {<br><br>    public static void main(String[] args) {<br>        long startTime = System.currentTimeMillis();<br><br>        long loadConfigStartTime = System.currentTimeMillis();<br>        ThreadSafeSingleton.loadConfig();<br>        long loadConfigEndTime = System.currentTimeMillis();<br>        long loadConfigTime = loadConfigEndTime - loadConfigStartTime;<br><br>        long firstCallStartTime = System.currentTimeMillis();<br>        ThreadSafeSingleton.getInstanceOptimized();<br>        long firstCallEndTime = System.currentTimeMillis();<br>        long firstCallTime = firstCallEndTime - firstCallStartTime;<br><br>        long secondCallStartTime = System.currentTimeMillis();<br>        ThreadSafeSingleton.getInstanceOptimized();<br>        long secondCallEndTime = System.currentTimeMillis();<br>        long secondCallTime = secondCallEndTime - secondCallStartTime;<br><br>        long endTime = System.currentTimeMillis();<br>        long totalTime = endTime - startTime;<br><br>        System.out.println(&quot;Load Config Time: &quot; + loadConfigTime + &quot; milliseconds&quot;);<br>        System.out.println(&quot;First Call Time: &quot; + firstCallTime + &quot; milliseconds&quot;);<br>        System.out.println(&quot;Second Call Time: &quot; + secondCallTime + &quot; milliseconds&quot;);<br>        System.out.println(&quot;Total Time: &quot; + totalTime + &quot; milliseconds&quot;);<br><br>    }<br><br>    public static void waitTime(){<br>        try {<br>            Thread.sleep(1000);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br>    }<br><br>}</pre><p>Let’s replace the eager singleton with the Thread safe singleton, and here’s the result :</p><p><strong>For the Thread Safe singleton :<br></strong>Load Config Time: 1 milliseconds<br>First Call Time: 3028 milliseconds<br>Second Call Time: 1008 milliseconds<br>Total Time: 4037 milliseconds</p><p><strong>For the Eager singleton :<br></strong>Load Config Time: 2022 milliseconds<br>First Call Time: 1008 milliseconds<br>Second Call Time: 1004 milliseconds<br>Total Time: 4034 milliseconds</p><p>I’ll let you draw the conclusions from those results.</p><p>If you are more of a visual person, feel free to watch the YouTube video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2P19tRdYHVY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2P19tRdYHVY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2P19tRdYHVY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a982bfaf40e51669a4067968bf3dc47e/href">https://medium.com/media/a982bfaf40e51669a4067968bf3dc47e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2840385fd550" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create your Password Generator in Jetpack Compose | Part 3 | Password Edit UI]]></title>
            <link>https://medium.com/@WhiteBatCodes/create-your-password-generator-in-jetpack-compose-part-3-password-edit-ui-12d8287ddac8?source=rss-fc7b5f06c16c------2</link>
            <guid isPermaLink="false">https://medium.com/p/12d8287ddac8</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[jetpack]]></category>
            <dc:creator><![CDATA[WhiteBatCodes]]></dc:creator>
            <pubDate>Mon, 29 May 2023 00:57:26 GMT</pubDate>
            <atom:updated>2023-05-29T15:51:42.610Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5RLPwmF9ADeoX4rfOmsFKw.png" /></figure><p>Password generators are commonly used to generate strong passwords for your accounts. This application is for you to make your own custom Password generator app and even store those passwords in a secure location for later usage.</p><p>In <a href="https://medium.com/@WhiteBatCodes/create-your-password-generator-in-jetpack-compose-interface-44959b8e1551?source=friends_link&amp;sk=d55ce3ff150d10a45783d552ee51e6b2">Part 2</a>, we have configured the logic to generate the passwords. In this part, we’ll configure a UI to allow the user to save additional data for the password.</p><p>Let’s start with the strings first to save time. In your <strong><em>values/strings.xml</em></strong> file add the following</p><pre>&lt;string name=&quot;create_new_password&quot;&gt;Create New password&lt;/string&gt;<br>&lt;string name=&quot;name&quot;&gt;Name*&lt;/string&gt;<br>&lt;string name=&quot;login&quot;&gt;Login*&lt;/string&gt;<br>&lt;string name=&quot;site_link&quot;&gt;Website Link&lt;/string&gt;<br>&lt;string name=&quot;description&quot;&gt;Description&lt;/string&gt;<br>&lt;string name=&quot;save&quot;&gt;Save&lt;/string&gt;</pre><p>Then, create an empty activity : <strong><em>PasswordEditorActivity</em></strong> and add the content and the starter composable with a preview like so :</p><pre>class PasswordEditorActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br><br>        setContent {<br>            PasswordEditor()<br>        }<br>    }<br>}<br><br><br>@Composable<br>fun PasswordEditor() {<br>   Text(&quot;ok&quot;)<br>}<br><br>@Preview(device = &quot;id:Nexus One&quot;, showSystemUi = true)<br>@Composable<br>fun PasswordEditorPreview() {<br>    PasswordVaultTheme {<br>        PasswordEditor()<br>    }<br>}</pre><p>Once the preview is good, let’s start with the title of the page. So in the method <strong><em>PasswordEditor()</em></strong>, add the following :</p><pre><br>@Composable<br>fun PasswordEditor() {<br>    Surface {<br>        Column(<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .padding(5.dp),<br>            horizontalAlignment = Alignment.CenterHorizontally,<br>            verticalArrangement = Arrangement.Center<br>        ) {<br>            Text(<br>                stringResource(id = R.string.create_new_password),<br>                modifier = Modifier.align(Alignment.CenterHorizontally),<br>                style = MaterialTheme.typography.headlineSmall<br>            )<br>        }<br>    }<br>}</pre><p>I have prepared a set of text fields that we will be using for this UI. Create a file <strong><em>Composables.kt</em></strong> inside the package <strong><em>ui.helpers</em></strong> : with the following content :</p><pre>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun PwdField(<br>    value: String,<br>    onChange: (String) -&gt; Unit,<br>    modifier: Modifier = Modifier,<br>    keyboardActions: KeyboardActions = KeyboardActions.Default,<br>    keyboardOptions: KeyboardOptions = KeyboardOptions.Default,<br>    label: String = &quot;Password&quot;,<br>    placeholder: String = &quot;Enter your Password&quot;<br>) {<br><br>    var isPasswordVisible by remember { mutableStateOf(false) }<br><br>    val trailingIcon = @Composable {<br>        IconButton(onClick = { isPasswordVisible = !isPasswordVisible }) {<br>            Icon(<br>                if (isPasswordVisible) Icons.Default.VisibilityOff else Icons.Default.Visibility,<br>                contentDescription = &quot;&quot;,<br>                tint = MaterialTheme.colorScheme.primary<br>            )<br>        }<br>    }<br><br><br>    TextField(<br>        value = value,<br>        onValueChange = onChange,<br>        modifier = modifier,<br>        trailingIcon = trailingIcon,<br>        keyboardOptions = keyboardOptions,<br>        keyboardActions = keyboardActions,<br>        placeholder = { Text(placeholder) },<br>        label = { Text(label) },<br>        singleLine = true,<br>        visualTransformation = if (isPasswordVisible) VisualTransformation.None else PasswordVisualTransformation(),<br><br>        )<br>}<br><br><br>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun TxtField(<br>    value: String,<br>    onChange: (String) -&gt; Unit,<br>    modifier: Modifier = Modifier,<br>    label: String = &quot;Login&quot;,<br>    placeholder: String = label,<br>    singleLine: Boolean = true,<br>    leadingIcon: @Composable (() -&gt; Unit)? = null,<br>    keyboardActions: KeyboardActions = KeyboardActions.Default,<br>    keyboardOptions: KeyboardOptions = KeyboardOptions.Default,<br>    maxLines: Int = Int.MAX_VALUE<br>) {<br><br>    TextField(<br>        value = value,<br>        onValueChange = onChange,<br>        modifier = modifier<br>            .fillMaxWidth(),<br>        leadingIcon = leadingIcon,<br>        keyboardOptions = keyboardOptions,<br>        keyboardActions = keyboardActions,<br>        placeholder = { Text(placeholder) },<br>        label = { Text(label) },<br>        singleLine = singleLine,<br>        visualTransformation = VisualTransformation.None,<br>        maxLines = maxLines<br>    )<br>}</pre><p>This file will need some extra icons for the password. Add the following implementation in your <strong><em>build.gradle</em></strong>, sync and import them :</p><pre>implementation &quot;androidx.compose.material:material-icons-extended:1.4.3&quot;</pre><p>Once we have our helpers, let’s create a password modal that will hold the password to be saved. The existing code already had a package called “<strong><em>modals.password</em></strong>” Let’s refactor this package to : “<strong><em>modals.passwordGen” </em></strong>and create a package <strong><em>modals.password </em></strong>and inside, add the data class <strong><em>SavedPassword.kt</em></strong><em>:</em></p><pre>data class SavedPassword(<br>    var title: String = &quot;&quot;,<br>    var id: Int = 0,<br>    var login: String = &quot;&quot;,<br>    var password: String = &quot;&quot;,<br>    var siteUrl: String = &quot;&quot;,<br>    var description: String = &quot;&quot;,<br>    var created: Long = Date().time,<br>    var updated: Long = Date().time<br>) {<br>    fun mandatoryFieldsExist(): Boolean {<br>        return title.isNotEmpty() &amp;&amp; login.isNotEmpty() &amp;&amp; password.isNotEmpty()<br>    }<br>}</pre><p>Back to the <strong><em>PasswordEditorActivity</em> </strong>let’s add an instance of that class that we’ll pass as a parameter to the text fields we’ll create right after. So in the first line inside the <strong><em>PasswordEditor()</em></strong> method, add the following :</p><pre>   var savedPassword by remember {<br>        mutableStateOf(SavedPassword())<br>    }</pre><p>then right after the <strong><em>Text</em></strong> composable, add the following :</p><pre>Spacer(Modifier.height(10.dp))<br>TxtField(<br>    value = savedPassword.title,<br>    onChange = {<br>        savedPassword = savedPassword.copy(title = it)<br>    },<br>    modifier = Modifier<br>        .padding(vertical= 5.dp),<br>    label = stringResource(id = R.string.name)<br>)<br>TxtField(<br>    value = savedPassword.login,<br>    onChange = {<br>        savedPassword = savedPassword.copy(login = it)<br>    },<br>    modifier = Modifier<br>        .padding(vertical= 5.dp),<br>    label = stringResource(id = R.string.login)<br>)<br>PwdField(<br>    value = savedPassword.password,<br>    onChange = {<br>        savedPassword = savedPassword.copy(password = it)<br>    },<br>    modifier = Modifier<br>        .fillMaxWidth()<br>        .padding(vertical= 5.dp)<br>)<br>TxtField(<br>    value = savedPassword.siteUrl,<br>    onChange = {<br>        savedPassword = savedPassword.copy(siteUrl = it)<br>    },<br>    modifier = Modifier<br>        .padding(vertical= 5.dp),<br>    label = stringResource(id = R.string.site_link)<br>)<br>TxtField(<br>    value = savedPassword.description,<br>    onChange = {<br>        savedPassword = savedPassword.copy(description = it)<br>    },<br>    modifier = Modifier<br>        .padding(vertical= 5.dp)<br>        .heightIn(min = 80.dp),<br>    label = stringResource(id = R.string.description)<br>)</pre><p>Now, let’s add the save button and add a context to close the current activity to go back to the launcher activity. Add the context after the <strong><em>savedPassword:</em></strong></p><pre>val context = LocalContext.current</pre><p>Under that description <strong><em>TxtField,</em></strong> add the following :</p><pre>Button(<br>        modifier = Modifier.fillMaxWidth(),<br>        onClick = {<br>            // send the data<br>            (context as Activity).finish()<br>        },<br>        enabled = savedPassword.mandatoryFieldsExist()<br>    ) {<br>        Text(stringResource(id = R.string.save))<br>    }<br><br>}</pre><p>Before we’ll close the activity, we’ll have to save the data, and this will be done in the next part.</p><p>So far, we have configured the interface of the Edit and what happens when the user clicks on Save to go back to the previous activity.</p><p>Now, let’s go back to our Password Generator activity and add the button save that will open the activity above. Inside the function <strong><em>PasswordGen() </em></strong>and after the “generate” button, add the following :</p><pre>Spacer(modifier = Modifier.height(10.dp))<br>Button(<br>    shape = RoundedCornerShape(5.dp),<br>    onClick = {<br>        context.startActivity(Intent(context,PasswordEditorActivity::class.java))<br>    },<br>    modifier = Modifier.fillMaxWidth(),<br>    enabled = generatedPassword.isNotEmpty()<br>) {<br>    Text(text = stringResource(id = R.string.save))<br>}</pre><p>If you run your activity, you’ll notice that the password field is not populated. That’s because we’re not passing it to the next activity. After you fill the mandatory attributes and click on save, you’ll be brought back to the starter activity, which is the password generator activity.</p><p>You can add a preview to see how everything looks like or run your application to see the result.</p><p>The GitHub code can be found here : <a href="https://github.com/Anass-ABEA/Jetpack-Compose-Password-Generator/tree/part_3">GitHub repo</a></p><p>Here’s a YouTube video if you want to follow the same steps more visually :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJHHVel9Vj10%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJHHVel9Vj10&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJHHVel9Vj10%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b18c858d00b021868391d6ffae799485/href">https://medium.com/media/b18c858d00b021868391d6ffae799485/href</a></iframe><p>You can read about part 2 here : <a href="https://medium.com/@WhiteBatCodes/create-your-password-generator-in-jetpack-compose-interface-44959b8e1551">Create your Password Generator in Jetpack Compose | Part 2 | PwdGen</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12d8287ddac8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create your Password Generator in Jetpack Compose | Part 4 | Save Password to Database]]></title>
            <link>https://medium.com/@WhiteBatCodes/create-your-password-generator-in-jetpack-compose-part-4-save-password-to-database-5bd93cfb9fe4?source=rss-fc7b5f06c16c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bd93cfb9fe4</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[WhiteBatCodes]]></dc:creator>
            <pubDate>Mon, 29 May 2023 00:57:17 GMT</pubDate>
            <atom:updated>2023-06-03T14:48:37.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOPtM_3FAD2O3xWpwQ2TwQ.png" /></figure><p>Password generators are commonly used to generate strong passwords for your accounts. This application is for you to make your own custom Password generator app and even store those passwords in a secure location for later usage.</p><p>In <a href="https://medium.com/@WhiteBatCodes/create-your-password-generator-in-jetpack-compose-part-3-password-edit-ui-12d8287ddac8">Part 3</a>, we have configured the UI for the save password interface. In this part, we’ll configure the logic, to send the saved password data between activities, create the database and save the password to the database.</p><p>Let’s start by editing the <strong><em>PasswordEditorActivity. </em></strong>We’ll load the password sent from the parent activity and pass it as the initial state for the UI. In the <strong><em>PasswordEditor()</em></strong> function, add the following :</p><pre>val context = LocalContext.current<br><br>var receivedPassword = when {<br>    Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU -&gt;<br>        (context as Activity).intent.getParcelableExtra(<br>            BEFORE_CREATE_EDIT_PASSWORD,<br>            SavedPassword::class.java<br>        )<br><br>    else -&gt; @Suppress(&quot;DEPRECATION&quot;) (context as Activity).intent.getSerializableExtra(<br>        BEFORE_CREATE_EDIT_PASSWORD<br>    ) as SavedPassword<br>}<br><br>if (receivedPassword == null) {<br>    receivedPassword = SavedPassword()<br>}</pre><p>We’re using this condition to check the API level if it’s less than 33, we can use the deprecated method if not we’ll use the new method. This will return to us the saved password.</p><p>The name of the Extra is saved in the <strong><em>PasswordGeneratorActivity</em></strong> inside a companion object that we will add in a bit.</p><p>To update the view with the retrieved password, change the <strong><em>savedPassword </em></strong>with the following and move it below the block of code you just added.</p><pre>var savedPassword by remember {<br>    mutableStateOf(receivedPassword)<br>}</pre><p>The Password editor activity should return a result that will be checked by the launcher activity. So before we finish the activity, we need to add that flag. Go to the Save button and call this method :</p><pre>sendResultAndFinish(savedPassword, context as Activity)</pre><p>then define the method as follows :</p><pre>fun sendResultAndFinish(savedPassword: SavedPassword, context: Activity) {<br>    context.setResult(RESULT_OK, Intent().putExtra(AFTER_CREATE_EDIT_PASSWORD,savedPassword))<br>    context.finish()<br>}</pre><p>Back to the <strong><em>PasswordGeneratorActivity</em></strong>, we’ll add the companion object inside the class:</p><pre>companion object {<br>    const val BEFORE_CREATE_EDIT_PASSWORD = &quot;Pwd-Before-Edit-Create&quot;<br>    const val AFTER_CREATE_EDIT_PASSWORD = &quot;Pwd-After-Edit-Create&quot;<br>}</pre><p>You’ll need to go back and import these variables in the <strong><em>PasswordEditorActivity.</em></strong> Then, we’ll need to register for the activity result to use it to start the Password Editor and get the result when the activity finishes. Right after the companion object, add the following :</p><pre>    val activityResultReg = registerForActivityResult(<br>        ActivityResultContracts.StartActivityForResult()<br>    ) {<br><br>            result -&gt;<br><br>        if (result.resultCode == Activity.RESULT_OK) {<br>            val data: Intent? = result.data<br><br>            if (data != null) {<br><br>                val receivedPassword = when {<br>                    Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU -&gt;<br>                        data.getParcelableExtra(<br>                            AFTER_CREATE_EDIT_PASSWORD,<br>                            SavedPassword::class.java<br>                        )<br><br>                    else -&gt; @Suppress(&quot;DEPRECATION&quot;) data.getSerializableExtra(<br>                        AFTER_CREATE_EDIT_PASSWORD<br>                    ) as SavedPassword<br>                }<br><br>                if (receivedPassword != null) {<br><br>                    // Save the password to the database<br>                    Log.d(&quot;Password&quot;, &quot;&quot; + receivedPassword)<br>                }<br><br>            }<br>        }<br><br>    }</pre><p>change the <strong><em>PasswordGen() </em></strong>method to use this variable as a parameter :</p><pre>fun PasswordGen(activityResultReg: ActivityResultLauncher&lt;Intent&gt;?)</pre><p>If you have a preview, you might need to pass null as a parameter.</p><p>In the onCreate, inside your setContent, pass the activityResultReg as a parameter:</p><pre>setContent {<br>    PasswordGen(activityResultReg)<br>}</pre><p>Now, let’s go to the Button to save the password and change the onclick method to :</p><pre>val intent = Intent(context, PasswordEditorActivity::class.java)<br>intent.putExtra(<br>    BEFORE_CREATE_EDIT_PASSWORD,<br>    SavedPassword(password = generatedPassword)<br>)<br><br>activityResultReg?.launch(intent)</pre><p>This will not work if you didn’t implement serializable in your <strong><em>SavedPassword</em></strong> data class. It should look something like this :</p><pre>data class SavedPassword(<br>    var title: String = &quot;&quot;,<br>    var id: Int = 0,<br>    var login: String = &quot;&quot;,<br>    var password: String = &quot;&quot;,<br>    var siteUrl: String = &quot;&quot;,<br>    var description: String = &quot;&quot;,<br>    var created: Long = Date().time,<br>    var updated: Long = Date().time<br>) : Serializable {<br>    fun mandatoryFieldsExist(): Boolean {<br>        return title.isNotEmpty() &amp;&amp; login.isNotEmpty() &amp;&amp; password.isNotEmpty()<br>    }<br>}</pre><p>You can now run your application and you should be able to see the password passed around from activity to activity, and you can check the Logcat to view the logs of the application. In the edit password UI, you’ll see the password pre-populated. Click on the eye button to show it.</p><p>Now that everything is set, let’s prepare our database.</p><p>In your <strong><em>build.gradle</em></strong> add the following :</p><p>in the dependencies :</p><pre>implementation &quot;androidx.room:room-ktx:2.5.1&quot;<br>kapt &quot;androidx.room:room-compiler:2.5.1&quot;<br>androidTestImplementation &quot;androidx.room:room-testing:2.5.1&quot;</pre><p>in the plugins :</p><pre>id &#39;kotlin-kapt&#39;</pre><p>Synchronize everything, and you should be ready to start working on your Database.</p><p>The next elements will be created in the same package as the SavedPassword. Let’s start with the Saved Password. Let’s add additional annotations. The result will look like this :</p><pre>@Entity(tableName = &quot;password&quot;)<br>data class SavedPassword(<br>    var title: String = &quot;&quot;,<br>    @PrimaryKey(autoGenerate = true) var id: Int = 0,<br>    var login: String = &quot;&quot;,<br>    var password: String = &quot;&quot;,<br>    var siteUrl: String = &quot;&quot;,<br>    var description: String = &quot;&quot;,<br>    @ColumnInfo(name=&quot;created_at&quot;) var created: Long = Date().time,<br>    @ColumnInfo(name=&quot;updated_at&quot;) var updated: Long = Date().time<br>) : Serializable {<br>  fun mandatoryFieldsExist(): Boolean {<br>      return title.isNotEmpty() &amp;&amp; login.isNotEmpty() &amp;&amp; password.isNotEmpty()<br>  }</pre><p>Let’s add the DAO by creating a new interface : <strong><em>SavedPasswordDao</em></strong></p><pre>@Dao<br>interface SavedPasswordDao {<br><br>    @Query(&quot;Select * FROM password ORDER BY updated_at DESC&quot;)<br>    fun getSavedPasswords(): List&lt;SavedPassword&gt;<br><br>    @Insert(onConflict = OnConflictStrategy.IGNORE)<br>    fun insert(savedPassword : SavedPassword)<br>}</pre><p>Then let’s add our famous database. We’ll set it as a singleton in our case to avoid creating multiple instances of it : <strong><em>SavedPasswordDb</em></strong></p><pre>@Database(entities = [SavedPassword::class], version = 1, exportSchema = false)<br>abstract class SavedPasswordDb : RoomDatabase() {<br><br>    abstract fun savedPasswordDao(): SavedPasswordDao<br><br>    companion object {<br><br>        @Volatile<br>        private var INSTANCE: SavedPasswordDb? = null<br><br>        fun getDatabase(context: Context): SavedPasswordDb {<br><br>            return INSTANCE ?: synchronized(this) {<br><br>                val instance = Room.databaseBuilder(<br>                    context.applicationContext,<br>                    SavedPasswordDb::class.java,<br>                    &quot;password_database&quot;<br>                ).build()<br><br>                INSTANCE = instance<br>                instance<br>            }<br><br>        }<br><br>    }<br><br>    override fun close() {<br>        super.close()<br>        INSTANCE = null;<br>    }<br>}</pre><p>Lastly, let’s create the repository : <strong><em>SavedPasswordRepo</em></strong></p><pre>class SavedPasswordRepo(private val savedPasswordDao : SavedPasswordDao) {<br><br>    @WorkerThread<br>    suspend fun insert(password : SavedPassword){<br>        withContext(Dispatchers.IO){<br>            savedPasswordDao.insert(password)<br>        }<br>    }<br><br>}</pre><p>Now, we’ll initialize our variables in the <strong><em>PasswordGeneratorActivity. </em></strong>On the class level, add the following variables :</p><pre>private lateinit var savedPwdRepo: SavedPasswordRepo<br>private lateinit var savedPwdDb: SavedPasswordDb</pre><p>Then let’s override two methods : <strong><em>onResume</em></strong> and <strong><em>onPause</em></strong> where we’ll create and start our database and close the database respectively:</p><pre>    override fun onResume() {<br>        super.onResume()<br>        savedPwdDb = SavedPasswordDb.getDatabase(baseContext)<br>        savedPwdRepo = SavedPasswordRepo(savedPwdDb.savedPasswordDao())<br>    }<br><br>    override fun onPause() {<br>        super.onPause()<br>        savedPwdDb.close()<br>    }<br>}</pre><p>Back to where we defined our “activityResultReg”, we’ll add the insert method to save the retrieved password. Before the <strong><em>Log.d</em></strong>, add the <strong><em>runBlocking </em></strong>to call the repository to add the password:</p><pre>if (receivedPassword != null) {<br><br>    runBlocking {<br>        savedPwdRepo.insert(receivedPassword)<br>    }<br><br>    Log.d(&quot;Password&quot;, &quot;&quot; + receivedPassword)<br>}</pre><p>For a better user experience, We’ll add some keyboard parameters like so :</p><p>First, load the focus manager before the Surface of the <strong><em>PasswordEditorActivity:</em></strong></p><pre>val focusManger = LocalFocusManager.current</pre><p>Then in each Field (text and password field), add the following settings :</p><pre>keyboardActions = KeyboardActions(<br>    onNext = {<br>        focusManger.moveFocus(FocusDirection.Down)<br>    }<br>),<br>keyboardOptions = KeyboardOptions(<br>    imeAction = ImeAction.Next<br>)</pre><p>For example, the first text field should look like :</p><pre>TxtField(<br>    value = savedPassword.title,<br>    onChange = {<br>        savedPassword = savedPassword.copy(title = it)<br>    },<br>    modifier = Modifier<br>        .padding(vertical = 5.dp),<br>    label = stringResource(id = R.string.name),<br>    keyboardActions = KeyboardActions(<br>        onNext = {<br>            focusManger.moveFocus(FocusDirection.Down)<br>        }<br>    ),<br>    keyboardOptions = KeyboardOptions(<br>        imeAction = ImeAction.Next<br>    )<br>)</pre><p>Do the same for all the fields but the last one. In the description field, update it to be :</p><pre>TxtField(<br>    value = savedPassword.description,<br>    onChange = {<br>        savedPassword = savedPassword.copy(description = it)<br>    },<br>    modifier = Modifier<br>        .padding(vertical = 5.dp)<br>        .heightIn(min = 80.dp),<br>    label = stringResource(id = R.string.description),<br>    keyboardActions = KeyboardActions(<br>        onDone  = {<br>            if(savedPassword.mandatoryFieldsExist()){<br>                sendResultAndFinish(savedPassword, context as Activity)<br>            }<br>        }<br>    ),<br>    keyboardOptions = KeyboardOptions(<br>        imeAction = ImeAction.Done<br>    )<br>)</pre><p>This will show a done button in the keyboard, and you can call the same method as the one in the save button when the user fills all the necessary data.</p><p>You can add a preview to see how everything looks like or run your application to see the result.</p><p>The GitHub code can be found here : <a href="https://github.com/Anass-ABEA/Jetpack-Compose-Password-Generator/tree/part_4">GitHub repo</a></p><p>Here’s a YouTube video if you want to follow the same steps more visually :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FUH3vth8p14o%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DUH3vth8p14o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FUH3vth8p14o%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e539b98b45f68bcdb9fd68b70fa43c5a/href">https://medium.com/media/e539b98b45f68bcdb9fd68b70fa43c5a/href</a></iframe><p>You can watch part 3 here : <a href="https://medium.com/@WhiteBatCodes/create-your-password-generator-in-jetpack-compose-part-3-password-edit-ui-12d8287ddac8">Create your Password Generator in Jetpack Compose | Part 3 | Password Edit UI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bd93cfb9fe4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create your Password Generator in Jetpack Compose | Part 2 | PwdGen]]></title>
            <link>https://medium.com/@WhiteBatCodes/create-your-password-generator-in-jetpack-compose-interface-44959b8e1551?source=rss-fc7b5f06c16c------2</link>
            <guid isPermaLink="false">https://medium.com/p/44959b8e1551</guid>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[WhiteBatCodes]]></dc:creator>
            <pubDate>Thu, 25 May 2023 21:48:57 GMT</pubDate>
            <atom:updated>2023-05-29T15:49:42.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3ITP1-ZNasIxx_FO1gEHA.png" /></figure><p>Password generators are commonly used to generate strong passwords for your accounts. This application is for you to make your own custom Password generator app and even store those passwords in a secure location for later usage.</p><p>In <a href="https://medium.com/@WhiteBatCodes/create-your-password-generator-in-jetpack-compose-interface-ec1419eca300">Part 1</a>, we have created the UI and now we are left with the logic to implement. We will configure the password generator, the logic for the buttons : Copy and Generate. Let’s get to it!</p><p>Let’s create the following packages : <strong><em>models.password.content</em></strong></p><p>In the package <strong><em>models.password </em></strong>we’ll create a Kotlin class : <strong><em>PasswordGenerator.kt</em></strong></p><p>It will be a data class with two parameters : <strong><em>password Size </em></strong>and <strong><em>password Content .</em></strong>The password Content is basically the password composition : Uppercase, Lowercase, Numeric &amp; Custom Password.</p><p>We’ll add a function called <strong><em>generatePassword </em></strong>that will return to us the generated password. The class should look like this :</p><pre>data class PasswordGenerator(<br>    var passwordSize: Int,<br>    var passwordContent: ArrayList&lt;PasswordContent&gt;<br>) {<br><br>    fun generatePassword() : String{<br>        var result = &quot;&quot;<br><br>        for(i in 0..passwordSize){<br>            val index = (Math.random()*passwordContent.size).toInt()<br>            result+= passwordContent[index].getRandom()<br>        }<br>        return result<br>    }<br>}</pre><p>Let’s go into the <strong><em>content</em></strong> package and create an interface <strong><em>PasswordContent</em></strong>:</p><pre>package com.whitebatcodes.passwordvault.models.password.contents<br><br>interface PasswordContent {<br><br>    var content : String<br><br>    fun getRandom(): Char{<br>        val index = (Math.random()*content.length).toInt()<br>        return content[index]<br>    }<br><br>}</pre><p>This interface will hold a single password composition and it has the method <strong><em>getRandom() </em></strong>That returns a random Char from the content String.</p><p>Now let’s implement this method using few Classes. In this context, I will be using singletons for the 3 classes : <strong><em>UpperPwdContent, LowerPwdContent </em></strong>&amp;<strong><em> NumericPwdContent </em></strong>They will look like so :</p><pre>package com.whitebatcodes.passwordvault.models.password.contents<br><br>data class LowerPwdContentImpl(override var content: String = &quot;abcdefghijklmnopqrstuvwxyz&quot;) : PasswordContent<br><br><br><br>object LowerPwdContent {<br>    private var instance : PasswordContent = LowerPwdContentImpl()<br><br>    fun getInstance() : PasswordContent{<br>        return instance<br>    }<br>}</pre><pre>package com.whitebatcodes.passwordvault.models.password.contents<br><br>data class UpperPwdContentImpl(override var content: String = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;) : PasswordContent<br><br><br>object UpperPwdContent {<br>    private var instance : PasswordContent = UpperPwdContentImpl()<br><br>    fun getInstance() : PasswordContent{<br>        return instance<br>    }<br>}</pre><pre>package com.whitebatcodes.passwordvault.models.password.contents<br><br>data class NumericPwdContentImpl(override var content: String = &quot;1234567890&quot;) : PasswordContent<br><br>object NumericPwdContent {<br>    private var instance : PasswordContent = NumericPwdContentImpl()<br><br>    fun getInstance() : PasswordContent{<br>        return instance<br>    }<br>}</pre><p>The Custom password content will not be static, as it will be built as needed:</p><pre>package com.whitebatcodes.passwordvault.models.password.contents<br><br>data class CustomPwdContent(override var content: String = &quot;?!@,-_&amp;#(){}[]&quot;) : PasswordContent</pre><p>Now that we have everything ready, let’s drop in design pattern : Builder in our <strong><em>PasswordGenerator</em></strong> class to build the password generator as needed. The class should look like this:</p><pre>data class PasswordGenerator(<br>    var passwordSize: Int,<br>    var passwordContent: ArrayList&lt;PasswordContent&gt;<br>) {<br><br>    fun generatePassword() : String{<br>        var result = &quot;&quot;<br><br>        for(i in 0..passwordSize){<br>            val index = (Math.random()*passwordContent.size).toInt()<br>            result+= passwordContent[index].getRandom()<br>        }<br>        return result<br>    }<br><br>    class Builder{<br>        private var instance = PasswordGenerator(8, ArrayList())<br><br>        fun addUpper(hasUpper : Boolean) : Builder{<br>            if(hasUpper) instance.passwordContent.add(UpperPwdContent.getInstance())<br>            return this<br>        }<br>        fun addLower(hasLower : Boolean) : Builder{<br>            if(hasLower) instance.passwordContent.add(LowerPwdContent.getInstance())<br>            return this<br>        }<br>        fun addNumeric(hasNumeric : Boolean) : Builder{<br>            if(hasNumeric) instance.passwordContent.add(NumericPwdContent.getInstance())<br>            return this<br>        }<br>        fun addCustom(hasCustom : Boolean, custom : CustomPwdContent) : Builder{<br>            if(hasCustom) instance.passwordContent.add(custom)<br>            return this<br>        }<br><br>        fun setSize(pwdSize : Int): Builder{<br>            instance.passwordSize = pwdSize<br>            return this<br>        }<br><br>        fun build() : PasswordGenerator{<br>            return instance<br>        }<br>    }<br>}</pre><p>Now that the logic is ready, we’ll have to update the <strong><em>PasswordGeneratorActivity.</em></strong> In the generate button, inside the onClick parameter, let’s add the following :</p><pre> val pwdGen = PasswordGenerator.Builder()<br>    .addUpper(isUpper)<br>    .addLower(isLower)<br>    .addNumeric(isNumeric)<br>    .addCustom(isCustom, CustomPwdContent(customPasswordSetting))<br>    .setSize(if (passwordSize.isEmpty()) 8 else passwordSize.toInt())<br>    .build()<br><br>generatedPassword = pwdGen.generatePassword()</pre><p>In the copy button, we’ll need a context to call the clipboard. So add the following variable near the state variables and then add the following code :</p><pre>val context = LocalContext.current</pre><pre>val clipboardManager = getSystemService(<br>    context,<br>    ClipboardManager::class.java<br>) as ClipboardManager<br>val clipData = ClipData.newPlainText(&quot;text&quot;, generatedPassword)<br>clipboardManager.setPrimaryClip(clipData)<br><br>Toast.makeText(context, &quot;Password Copied&quot;,Toast.LENGTH_SHORT).show()</pre><p>And we’re done! You can run your application to see the generated password.</p><p>The GitHub code can be found here : <a href="https://github.com/Anass-ABEA/Jetpack-Compose-Password-Generator/tree/part_2">GitHub repo</a></p><p>Here’s a YouTube video if you want to follow the same steps more visually :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fv9luSlXZBiE&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dv9luSlXZBiE&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bdde84718dddf6d88cb8e0d84fff5b4/href">https://medium.com/media/8bdde84718dddf6d88cb8e0d84fff5b4/href</a></iframe><p>You can read about part 1 here : <a href="https://medium.com/@WhiteBatCodes/create-your-password-generator-in-jetpack-compose-interface-ec1419eca300">Create your Password Generator in Jetpack Compose | Part 1 | Interface</a></p><p>Part 3 can be found here : <a href="https://medium.com/@WhiteBatCodes/create-your-password-generator-in-jetpack-compose-part-3-password-edit-ui-12d8287ddac8">Create your Password Generator in Jetpack Compose | Part 3 | Password Edit UI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44959b8e1551" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create your Password Generator in Jetpack Compose | Part 1 | Interface]]></title>
            <link>https://medium.com/@WhiteBatCodes/create-your-password-generator-in-jetpack-compose-interface-ec1419eca300?source=rss-fc7b5f06c16c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec1419eca300</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[WhiteBatCodes]]></dc:creator>
            <pubDate>Thu, 25 May 2023 21:48:02 GMT</pubDate>
            <atom:updated>2023-05-29T00:56:42.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOb1t0wrvmpuXw_a4loXqw.png" /></figure><p>Password generators are commonly used to generate strong passwords for your accounts. This application is for you to make your own custom Password generator app and even store those passwords in a secure location for later usage.</p><p>This is going to be part 1 of this project. In this part, we’ll create the UI for the password generator, as you can see in the screenshot above.</p><p>Let’s start with a new empty Activity as a starter activity. After you create your Activity. Make sure it’s set to the starter activity in your manifest by moving the<strong><em> intent-filter</em></strong> block from <strong><em>MainActivity </em></strong>to your class, in this project I called it <strong><em>PasswordGeneratorActivity</em></strong>. The result should look something like this :</p><pre>&lt;application<br>    android:allowBackup=&quot;true&quot;<br>    android:dataExtractionRules=&quot;@xml/data_extraction_rules&quot;<br>    android:fullBackupContent=&quot;@xml/backup_rules&quot;<br>    android:icon=&quot;@mipmap/ic_launcher&quot;<br>    android:label=&quot;@string/app_name&quot;<br>    android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;<br>    android:supportsRtl=&quot;true&quot;<br>    android:theme=&quot;@style/Theme.PasswordVault&quot;<br>    tools:targetApi=&quot;31&quot;&gt;<br>    &lt;activity<br>        android:name=&quot;.PasswordGeneratorActivity&quot;<br>        android:exported=&quot;true&quot;&gt;<br>        &lt;intent-filter&gt;<br>            &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;<br><br>            &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>        &lt;/intent-filter&gt;<br>    &lt;/activity&gt;<br>    &lt;activity<br>        android:name=&quot;.MainActivity&quot;<br>        android:exported=&quot;true&quot;<br>        android:theme=&quot;@style/Theme.PasswordVault&quot; /&gt;<br>&lt;/application&gt;</pre><p>Before we dig into the UI, we’ll create some Strings that we can translate later on. Go to <strong><em>/res/values/strings.xml </em></strong>and add the following strings:</p><pre>&lt;string name=&quot;generate_a_password&quot;&gt;Generate a Password&lt;/string&gt;<br>&lt;string name=&quot;generate&quot;&gt;Generate&lt;/string&gt;<br>&lt;string name=&quot;copy&quot;&gt;Copy&lt;/string&gt;<br>&lt;string name=&quot;upper_case&quot;&gt;Upper Case&lt;/string&gt;<br>&lt;string name=&quot;lower_case&quot;&gt;Lower Case&lt;/string&gt;<br>&lt;string name=&quot;numeric&quot;&gt;Numeric&lt;/string&gt;<br>&lt;string name=&quot;click_on_generate&quot;&gt;Click on Generate&lt;/string&gt;<br>&lt;string name=&quot;password_size&quot;&gt;Password Size&lt;/string&gt;</pre><p>In your <strong><em>PasswordGeneratorActivity, </em></strong>add the content in your <strong><em>onCreate()</em></strong><em> </em>as follows :</p><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br><br>    setContent {<br>        PasswordGen()<br>    }<br>}</pre><p>Now let’s start defining the password generator interface!</p><p>First, we’ll create a Column that will host the generated password and a butty copy, to allow the user to copy the value :</p><pre>@Composable<br>fun PasswordGen() {<br>    var generatedPassword by remember { mutableStateOf(&quot;&quot;) }<br><br>    Surface {<br>        Column(<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .padding(horizontal = 10.dp),<br>            verticalArrangement = Arrangement.Center<br>        ) { // parent column<br>            Text(<br>                stringResource(id = R.string.generate_a_password),<br>                modifier = Modifier.align(CenterHorizontally),<br>                style = MaterialTheme.typography.headlineSmall<br>            ) // title of the page<br>            Spacer(modifier = Modifier.height(10.dp))<br><br>            Column(<br>                verticalArrangement = Arrangement.Center<br>            ) { // generated password column<br>                Row(<br>                    verticalAlignment = Alignment.CenterVertically,<br>                    horizontalArrangement = Arrangement.Center<br>                ) {<br>                    Text(<br>                        text = generatedPassword.ifEmpty { stringResource(id = R.string.click_on_generate) },<br>                        modifier = Modifier.weight(1f)<br>                    )<br>                    Spacer(modifier = Modifier.width(5.dp))<br>                    Button(<br>                        onClick = { /*TODO*/ },<br>                        enabled = generatedPassword.isNotEmpty(),<br>                        shape = RoundedCornerShape(5.dp)<br>                    ) {<br>                        Text(stringResource(id = R.string.copy))<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>This should display a title, a textfield and a copy button. Note that in the code, the textfield will display the string value “click on generate” if the generated password string is empty. You can see the password if you change the initial state of the generated password by adding any non-empty string.</p><p>Next, the tricky part! We’ll have to create 3 labeled checkboxes, 1 Editable checkbox, a row for the password size and at last, the Generate button.</p><p>For the Labeled checkboxes, we’ll have to define the components separately to make it simpler and reusable :</p><pre>@Composable<br>fun LabeledCheckbox(label: String, onCheckChange: () -&gt; Unit, isChecked: Boolean) {<br>    Row(<br>        modifier = Modifier<br>            .clickable(<br>                onClick = onCheckChange<br>            )<br>            .fillMaxWidth()<br>            .padding(vertical = 5.dp)<br>    ) {<br>        Checkbox(checked = isChecked, onCheckedChange = null)<br>        Text(text = label)<br>    }<br>}</pre><p>The row here is what will be clickable, as the checkbox doesn’t have a default label for it. So here, once we click on the row, the checkbox will either be checked or unchecked. We pass this method as a paramter to the function, and we also pass the label to display and the intial state of the checkbox.</p><p>For the Editable checkbox, we can base it on the previous checkbox and add a TextField instead of a simple Text. This will allow the user to edit the data. The method should look like this :</p><pre>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun EditableCheckBox(<br>    value: String,<br>    onCheckChange: () -&gt; Unit,<br>    onValueChange: (String) -&gt; Unit,<br>    isChecked: Boolean<br>) {<br>    Row(<br>        modifier = Modifier<br>            .clickable(<br>                onClick = onCheckChange<br>            )<br>            .fillMaxWidth()<br>            .padding(vertical = 5.dp),<br>        verticalAlignment = CenterVertically<br>    ) {<br>        Checkbox(checked = isChecked, onCheckedChange = null)<br>        TextField(value = value, onValueChange = onValueChange)<br>    }<br>}</pre><p>Note that the checkbox logic is the same, but we added here a method for the value of the TextField to listen to a change in the field.</p><p>Let’s add these checkboxes to the <strong><em>PasswordGen </em></strong>method and see how it looks like:</p><pre>@Composable<br>fun PasswordGen() {<br>    var generatedPassword by remember { mutableStateOf(&quot;&quot;) }<br>    var customPasswordSetting by remember { mutableStateOf(&quot;@{}&quot;) }<br><br>    var isUpper by remember { mutableStateOf(true) }<br>    var isLower by remember { mutableStateOf(true) }<br>    var isNumeric by remember { mutableStateOf(false) }<br>    var isCustom by remember { mutableStateOf(false) }<br><br>    Surface {<br>        Column(<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .padding(horizontal = 10.dp),<br>            verticalArrangement = Arrangement.Center<br>        ) {<br>            Text(<br>                stringResource(id = R.string.generate_a_password),<br>                modifier = Modifier.align(CenterHorizontally),<br>                style = MaterialTheme.typography.headlineSmall<br>            )<br>            Spacer(modifier = Modifier.height(10.dp))<br><br>            Column(<br>                verticalArrangement = Arrangement.Center<br>            ) {<br>                Row(<br>                    verticalAlignment = Alignment.CenterVertically,<br>                    horizontalArrangement = Arrangement.Center<br>                ) {<br>                    Text(<br>                        text = generatedPassword.ifEmpty { stringResource(id = R.string.click_on_generate) },<br>                        modifier = Modifier.weight(1f)<br>                    )<br>                    Spacer(modifier = Modifier.width(5.dp))<br>                    Button(<br>                        onClick = { /*TODO*/ },<br>                        enabled = generatedPassword.isNotEmpty(),<br>                        shape = RoundedCornerShape(5.dp)<br>                    ) {<br>                        Text(stringResource(id = R.string.copy))<br>                    }<br>                }<br>            }<br><br>            Spacer(modifier = Modifier.height(10.dp))<br><br>            LabeledCheckbox(<br>                label = stringResource(id = R.string.upper_case),<br>                onCheckChange = {<br>                    isUpper = !isUpper<br>                },<br>                isChecked = isUpper<br>            )<br>            LabeledCheckbox(<br>                label = stringResource(id = R.string.lower_case),<br>                onCheckChange = {<br>                    isLower = !isLower<br>                },<br>                isChecked = isLower<br>            )<br>            LabeledCheckbox(<br>                label = stringResource(id = R.string.numeric),<br>                onCheckChange = {<br>                    isNumeric = !isNumeric<br>                },<br>                isChecked = isNumeric<br>            )<br>            EditableCheckBox(<br>                value = customPasswordSetting,<br>                onCheckChange = {<br>                    if (customPasswordSetting.isNotEmpty())<br>                        isCustom = !isCustom<br>                },<br>                isChecked = isCustom,<br>                onValueChange = {<br>                    if (it.isEmpty()) {<br>                        isCustom = false<br>                    }<br>                    customPasswordSetting = it<br>                }<br>            )<br><br>        }<br>    }<br>}</pre><p>With this like so, you’ll be able to view the 4 fields and also see that the first 2 fields are checked (the default state) and also we have added a variable called <strong><em>customPasswordSetting. </em></strong>This variable is the default value of the custom password text field. That field will serve us as to improve the strength of the generated password. This will give the user more flexibility when generating the password.</p><p>Let’s now jump to the password size. We’ll have to use a text field too, but we’ll customize it to allow the users to input numbers only :</p><pre>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun PasswordSize(passwordSize: String, onValueChange: (String) -&gt; Unit) {<br>    Row(<br>        modifier = Modifier.fillMaxWidth(),<br>        verticalAlignment = CenterVertically<br>    ) {<br>        Text(<br>            text = stringResource(id = R.string.password_size),<br>            modifier = Modifier.weight(1f)<br>        )<br>        TextField(<br>            value = passwordSize,<br>            onValueChange = onValueChange,<br>            keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),<br>            placeholder = { Text(&quot;Max 200&quot;) },<br>            modifier = Modifier.weight(1f)<br>        )<br>    }<br>}</pre><p>In this method, the keyboard is set to a numeric keyboard and the placeholder is set to display maximum 200.</p><p>Let’s add this method and our Button to the <strong><em>PasswordGen()</em></strong> method. With everything in place, it should look like this:</p><pre>@Composable<br>fun PasswordGen() {<br>    var generatedPassword by remember { mutableStateOf(&quot;&quot;) }<br>    var passwordSize by remember { mutableStateOf(&quot;8&quot;) }<br>    var customPasswordSetting by remember { mutableStateOf(&quot;?!@,-_&amp;#(){}[]&quot;) }<br><br>    var isUpper by remember { mutableStateOf(true) }<br>    var isLower by remember { mutableStateOf(true) }<br>    var isNumeric by remember { mutableStateOf(false) }<br>    var isCustom by remember { mutableStateOf(false) }<br><br>    Surface {<br>        Column(<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .padding(horizontal = 10.dp),<br>            verticalArrangement = Arrangement.Center<br>        ) {<br>            Text(<br>                stringResource(id = R.string.generate_a_password),<br>                modifier = Modifier.align(CenterHorizontally),<br>                style = MaterialTheme.typography.headlineSmall<br>            )<br>            Spacer(modifier = Modifier.height(10.dp))<br><br>            Column(<br>                verticalArrangement = Arrangement.Center<br>            ) {<br>                Row(<br>                    verticalAlignment = Alignment.CenterVertically,<br>                    horizontalArrangement = Arrangement.Center<br>                ) {<br>                    Text(<br>                        text = generatedPassword.ifEmpty { stringResource(id = R.string.click_on_generate) },<br>                        modifier = Modifier.weight(1f)<br>                    )<br>                    Spacer(modifier = Modifier.width(5.dp))<br>                    Button(<br>                        onClick = { /*TODO*/ },<br>                        enabled = generatedPassword.isNotEmpty(),<br>                        shape = RoundedCornerShape(5.dp)<br>                    ) {<br>                        Text(stringResource(id = R.string.copy))<br>                    }<br>                }<br>            }<br><br>            Spacer(modifier = Modifier.height(10.dp))<br><br>            LabeledCheckbox(<br>                label = stringResource(id = R.string.upper_case),<br>                onCheckChange = {<br>                    isUpper = !isUpper<br>                },<br>                isChecked = isUpper<br>            )<br>            LabeledCheckbox(<br>                label = stringResource(id = R.string.lower_case),<br>                onCheckChange = {<br>                    isLower = !isLower<br>                },<br>                isChecked = isLower<br>            )<br>            LabeledCheckbox(<br>                label = stringResource(id = R.string.numeric),<br>                onCheckChange = {<br>                    isNumeric = !isNumeric<br>                },<br>                isChecked = isNumeric<br>            )<br>            EditableCheckBox(<br>                value = customPasswordSetting,<br>                onCheckChange = {<br>                    if (customPasswordSetting.isNotEmpty())<br>                        isCustom = !isCustom<br>                },<br>                isChecked = isCustom,<br>                onValueChange = {<br>                    if (it.isEmpty()) {<br>                        isCustom = false<br>                    }<br>                    customPasswordSetting = it<br>                }<br>            )<br><br>            PasswordSize(<br>                passwordSize = passwordSize,<br>                onValueChange = {<br>                    if ((it.isNotEmpty() &amp;&amp; it.toInt() &lt; 200) || it.isEmpty()) {<br>                        passwordSize = it<br>                    }<br>                }<br>            )<br>            Spacer(modifier = Modifier.height(10.dp))<br>            Button(<br>                shape = RoundedCornerShape(5.dp),<br>                onClick = { /*TODO*/ },<br>                modifier = Modifier.fillMaxWidth(),<br>                enabled = (isUpper || isLower || isCustom || isNumeric) &amp;&amp; passwordSize.isNotEmpty() &amp;&amp; passwordSize.toInt() &gt; 0<br>            ) {<br>                Text(text = stringResource(id = R.string.generate))<br>            }<br><br>        }<br>    }<br>}</pre><p>Here, the generate button will be hidden unless one of the checkboxes is checked, the password is not empty and the password is greater than 0.</p><p>Notice that, in the custom password, the value change changes the value of the check if the field is empty. If the user didn’t enter any value, the checkbox should be unchecked.</p><p>You can add a preview to see how everything looks like or run your application to see the result.</p><p>The GitHub code can be found here : <a href="https://github.com/Anass-ABEA/Jetpack-Compose-Password-Generator/tree/part_1">GitHub repo</a></p><p>Here’s a YouTube video if you want to follow the same steps more visually :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FvRuvY1CYaGw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DvRuvY1CYaGw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FvRuvY1CYaGw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/912d5aa9e778275e2ce9c43329294231/href">https://medium.com/media/912d5aa9e778275e2ce9c43329294231/href</a></iframe><p>You can watch part 2 here : <a href="https://medium.com/@WhiteBatCodes/create-your-password-generator-in-jetpack-compose-interface-44959b8e1551">Create your Password Generator in Jetpack Compose | PwdGen</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec1419eca300" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make a Calculator in Android Studio | Part 4 | Sign Changing and styling]]></title>
            <link>https://medium.com/@WhiteBatCodes/how-to-make-a-calculator-in-android-studio-part-4-sign-changing-and-styling-7459ee8fafe6?source=rss-fc7b5f06c16c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7459ee8fafe6</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[WhiteBatCodes]]></dc:creator>
            <pubDate>Sat, 20 May 2023 16:58:26 GMT</pubDate>
            <atom:updated>2023-05-20T17:16:56.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Jm8ok4p2GQs5mj__4x3og.png" /></figure><p>In Part 3 ( <a href="https://medium.com/@WhiteBatCodes/how-to-make-a-calculator-in-android-studio-part-2-adding-a-numpad-for-simple-sum-124ae40426eb">find it here</a> ) we have added a numpad to perform complex arithmetic. In this part, I will show you how to change number signs and add a history to allow the user to see the operation they performed.</p><p>The first thing we will do is to Update the <strong><em>activity_main.xml</em></strong> file to add all the buttons and place them as needed. We’ll only add a button between the plus button and the erase button:</p><pre>&lt;Button<br>    android:id=&quot;@+id/btn_plus_minus&quot;<br>    style=&quot;@style/Calculator.Buttons.Operations&quot;<br>    android:layout_width=&quot;wrap_content&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:layout_weight=&quot;1&quot;<br>    android:text=&quot;+/-&quot; /&gt;</pre><p>Let’s add a new string in <strong><em>/res/values/strings.xml</em></strong></p><pre>&lt;string name=&quot;last_operation&quot;&gt;Last Operation:&lt;/string&gt;</pre><p>Let’s replace the entire <strong><em>LinearLayout</em></strong> before the <strong><em>TableLayout</em></strong> to this:</p><pre>&lt;LinearLayout<br>    android:id=&quot;@+id/linearLayout&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;100dp&quot;<br>    android:gravity=&quot;center&quot;<br>    android:orientation=&quot;vertical&quot;<br>    android:padding=&quot;10dp&quot;<br>    app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>    app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>    app:layout_constraintTop_toTopOf=&quot;parent&quot;&gt;<br><br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:layout_weight=&quot;1&quot;<br>        android:orientation=&quot;horizontal&quot;&gt;<br>        &lt;TextView<br>            android:id=&quot;@+id/tv_value&quot;<br>            android:layout_width=&quot;0dp&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_weight=&quot;1&quot;<br>            android:text=&quot;&quot; /&gt;<br><br>        &lt;Button<br>            android:id=&quot;@+id/btn_clear&quot;<br>            style=&quot;@style/Calculator.Buttons.Operations&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:text=&quot;@string/clear&quot; /&gt;<br><br>    &lt;/LinearLayout&gt;<br><br>    &lt;TextView<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;@string/last_operation&quot; /&gt;<br>    &lt;TextView<br>        android:id=&quot;@+id/tv_history&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;&quot; /&gt;<br><br>&lt;/LinearLayout&gt;</pre><p>This is to add the new text views to display the newly added string and the history.</p><p>Next stop is to add the new <strong><em>TextView </em></strong>&amp; <strong><em>Button</em></strong> in our java logic. Starting with defining the variable :</p><pre>private Button btnPlusMinus;<br>private TextView tvHistory;</pre><p>Let’s initialize these variables in the <strong><em>initViews()</em></strong> method</p><pre>this.btnPlusMinus = findViewById(R.id.btn_plus_minus);<br>this.tvHistory = findViewById(R.id.tv_history);</pre><p>Then update the <strong><em>clickListeners() </em></strong>method by adding the following listeners for the new buttons and update the listener :</p><pre>this.btnPlusMinus.setOnClickListener(v-&gt;{<br>    String value = this.tvValue.getText().toString();<br>    if(value.length() == 0 || value.endsWith(&quot; &quot;)) return;<br>    int index = value.lastIndexOf(&quot; &quot;);<br><br>    if(index!=-1){ // 3 * 5<br>        Double lastNumber = Double.parseDouble(value.substring(index+1));<br>        value = value.substring(0,index+1)+ (-lastNumber);<br>        this.tvValue.setText(value);<br>    }else{<br>        this.tvValue.setText(String.valueOf(-Double.parseDouble(value)));<br>    }<br>});<br></pre><p>In this part, we are checking if the last element is an operation, wich ends with a space. Here we do nothing. If it’s not the case, then the last element in the string is a number, so let’s get the last index of the operation to get the number and then, we’ll parse it to a double and replace it with its negative value.</p><p>Next step is to update the equals button to avoind long numbers after the decimal point. Here we’ll show only 4 digits after the decimal point and we’ll also update the history text view with the value obtained form the user input.</p><pre>this.btnEquals.setOnClickListener((v) -&gt; {<br>    String value = this.tvValue.getText().toString();<br>    this.tvHistory.setText(value);<br><br>    double result = EvaluateOperations.evaluateWithPriority(value);<br>    DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols();<br>    DecimalFormat df = new DecimalFormat(&quot;#.####&quot;,formatSymbols);<br><br>    this.tvValue.setText(df.format(result));<br>});</pre><p>And we’re done! You can run your application to see the changes. 😉</p><p>Here’s a YouTube video if you want to follow the same steps more visually :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FISv8G9pnXl8&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DISv8G9pnXl8&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FISv8G9pnXl8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/260a375c42bc024a59747f9ee312b147/href">https://medium.com/media/260a375c42bc024a59747f9ee312b147/href</a></iframe><p>The GitHub code can be found here : <a href="https://github.com/Anass-ABEA/Android-Calculator/tree/Final_Part">GitHub Repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7459ee8fafe6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Login Page in Jetpack Compose]]></title>
            <link>https://medium.com/@WhiteBatCodes/simple-login-page-in-jetpack-compose-9c92af690234?source=rss-fc7b5f06c16c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c92af690234</guid>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[ui-design]]></category>
            <category><![CDATA[compose-ui]]></category>
            <category><![CDATA[login]]></category>
            <dc:creator><![CDATA[WhiteBatCodes]]></dc:creator>
            <pubDate>Fri, 19 May 2023 21:36:27 GMT</pubDate>
            <atom:updated>2023-05-19T21:36:27.161Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kDdhhGVjXFf1xbEieLEvQw.png" /></figure><p>This post is based on my YouTube video that you can <a href="https://www.youtube.com/watch?v=t5O3omAI-6c&amp;ab_channel=WhiteBatCodes">find here</a> or at the end of this post</p><p>In this post We’ll see how to create the simple login interface using JetPack Compose.</p><p>After you create an empty Jetpack project, you’ll have the default <strong><em>MainActivity.kt</em></strong> class. We’ll make some changes to the preview. We’ll use it later for the Login Page. The <strong><em>MainActivity </em></strong>will serve as the page that the user can access to after they successfully login.</p><p>Let’s add at the bottom two preview functions :</p><pre>@Preview(showBackground = true, device = &quot;id:Nexus One&quot;, showSystemUi = true)<br>@Composable<br>fun GreetingPreview() {<br>    MyLoginApplicationTheme {<br>        Greeting(&quot;Android&quot;)<br>    }<br>}<br><br>@Preview(showBackground = true, device = &quot;id:Nexus One&quot;, showSystemUi = true)<br>@Composable<br>fun GreetingPreviewDark() {<br>    MyLoginApplicationTheme(darkTheme = true) {<br>        Greeting(&quot;Android&quot;)<br>    }<br>}</pre><p>The dark theme looks no different from the light mode because our preview doesn’t use the Surface as a parent. Let’s update the <strong><em>Greetings()</em></strong> method to make that happen</p><pre>@Composable<br>fun Greeting(name: String, modifier: Modifier = Modifier) {<br>    Surface {<br>        Column(<br>            verticalArrangement = Arrangement.Center,<br>            horizontalAlignment = Alignment.CenterHorizontally,<br>            modifier = Modifier.fillMaxSize()<br>        ) {<br>            Text(<br>                text = &quot;Hello $name!&quot;,<br>                modifier = modifier<br>            )<br>        }<br>    }<br>}</pre><p>This is enough to update the dark them preview and also to center everything in the middle of the screen.</p><p>you can also Update the <strong>onCreate() </strong>method of the <strong><em>MainActivity.kt</em></strong> class to show the changes in your application after running it</p><pre>setContent {<br>    MyLoginApplicationTheme {<br>        Greeting(&quot;Android&quot;)<br>    }<br>}</pre><p>Enough with the <strong><em>MainActivity</em></strong>, let’s now create our <strong><em>LoginActivity.kt</em></strong> class<br>I will let you decide on the best approach you want to do it but my result looks like this after the creation :</p><pre>package com.whitebatcodes.myloginapplication<br><br>import android.os.Bundle<br>import androidx.activity.ComponentActivity<br>import androidx.activity.compose.setContent<br>import com.whitebatcodes.myloginapplication.interfaces.LoginForm<br>import com.whitebatcodes.myloginapplication.ui.theme.MyLoginApplicationTheme<br><br>class LoginActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br><br>        setContent{<br>            <br>        }<br>    }<br>}</pre><p>in the <strong><em>setContent </em></strong>block, add the following</p><pre>MyLoginApplicationTheme {<br>    LoginForm()<br>}</pre><p>Now we’ll have to define the<strong><em> LoginForm()</em></strong> method somewhere. I chose to create a new Kotlin file where I’ll have all my views. The form will contain: a Login Field, a Password Field, a checkbox with a label and a button. Let’s define each element separately:</p><pre>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun LoginField(<br>    value: String,<br>    onChange: (String) -&gt; Unit,<br>    modifier: Modifier = Modifier,<br>    label: String = &quot;Login&quot;,<br>    placeholder: String = &quot;Enter your Login&quot;<br>) {<br><br>    val focusManager = LocalFocusManager.current<br>    val leadingIcon = @Composable {<br>        Icon(<br>            Icons.Default.Person,<br>            contentDescription = &quot;&quot;,<br>            tint = MaterialTheme.colorScheme.primary<br>        )<br>    }<br><br>    TextField(<br>        value = value,<br>        onValueChange = onChange,<br>        modifier = modifier,<br>        leadingIcon = leadingIcon,<br>        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),<br>        keyboardActions = KeyboardActions(<br>            onNext = { focusManager.moveFocus(FocusDirection.Down) }<br>        ),<br>        placeholder = { Text(placeholder) },<br>        label = { Text(label) },<br>        singleLine = true,<br>        visualTransformation = VisualTransformation.None<br>    )<br>}</pre><p>The <strong><em>LoginField() </em></strong>method contains uses a leading icon that you can find in the default Icons class, the Field also changes the IME to Next so that we move the focus to the next field, in this case the password field. We’ll need to use the focus manager for that. We also added a label and a placehoder with the default values passed as parameters, made the field single line and didn’t set any visual transformation. This parameter is relevant for the Password field.</p><p>The password field will require some icons that don’t exist in the default Icons class. Go to your <strong><em>build.gradle (app)</em></strong> and add the following implementation :</p><pre>implementation &quot;androidx.compose.material:material-icons-extended:1.4.3&quot;</pre><p>The password field method is as follows :</p><pre>@Composable<br>fun PasswordField(<br>    value: String,<br>    onChange: (String) -&gt; Unit,<br>    submit: () -&gt; Unit,<br>    modifier: Modifier = Modifier,<br>    label: String = &quot;Password&quot;,<br>    placeholder: String = &quot;Enter your Password&quot;<br>) {<br><br>    var isPasswordVisible by remember { mutableStateOf(false) }<br><br>    val leadingIcon = @Composable {<br>        Icon(<br>            Icons.Default.Key,<br>            contentDescription = &quot;&quot;,<br>            tint = MaterialTheme.colorScheme.primary<br>        )<br>    }<br>    val trailingIcon = @Composable {<br>        IconButton(onClick = { isPasswordVisible = !isPasswordVisible }) {<br>            Icon(<br>                if (isPasswordVisible) Icons.Default.VisibilityOff else Icons.Default.Visibility,<br>                contentDescription = &quot;&quot;,<br>                tint = MaterialTheme.colorScheme.primary<br>            )<br>        }<br>    }<br><br><br>    TextField(<br>        value = value,<br>        onValueChange = onChange,<br>        modifier = modifier,<br>        leadingIcon = leadingIcon,<br>        trailingIcon = trailingIcon,<br>        keyboardOptions = KeyboardOptions(<br>            imeAction = ImeAction.Done,<br>            keyboardType = KeyboardType.Password<br>        ),<br>        keyboardActions = KeyboardActions(<br>            onDone = { submit() }<br>        ),<br>        placeholder = { Text(placeholder) },<br>        label = { Text(label) },<br>        singleLine = true,<br>        visualTransformation = if (isPasswordVisible) VisualTransformation.None else PasswordVisualTransformation()<br>    )<br>}</pre><p>We don’t need a focus manager for the password as the IME button is Done and we’ll submit the form. We’ll also need a mutable variable to make to recompose the field if the password is visible. this is controlled using the <strong><em>IconButton </em></strong>configured in the trailingIcon attribute. We’ll also change the keyboard type to disable the auto correct and the clipboard suggestions. We’ll also configure the visual transformation based on the variable “<strong><em>isPasswordVisible</em></strong>” to either show or hide the password. We’ll also add a new functions: <strong><em>submit()</em></strong> that will be triggered when the done button in the keyboard is pressed.</p><p>We can preview this by changing the method<strong><em> LoginForm()</em></strong></p><pre>@Composable<br>fun LoginForm() {<br>    Surface {<br>        Column(<br>            verticalArrangement = Arrangement.Center,<br>            horizontalAlignment = Alignment.CenterHorizontally,<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .padding(horizontal = 30.dp)<br>        ) {<br>            LoginField(<br>                value = &quot;login&quot;,<br>                onChange = { },<br>                modifier = Modifier.fillMaxWidth()<br>            )<br>            PasswordField(<br>                value = &quot;password&quot;,<br>                onChange = { },<br>                submit = { },<br>                modifier = Modifier.fillMaxWidth()<br>            )<br>        }<br>    }<br>}</pre><p>Now we will have to add a checkbox to remember the user login. We will not define saving the login nor the authentication process in this tutorial.</p><p>For the labeled checkbox, the method should look like this:</p><pre>@Composable<br>fun LabeledCheckbox(<br>    label: String,<br>    onCheckChanged: () -&gt; Unit,<br>    isChecked: Boolean<br>) {<br><br>    Row(<br>        Modifier<br>            .clickable(<br>                onClick = onCheckChanged<br>            )<br>            .padding(4.dp)<br>    ) {<br>        Checkbox(checked = isChecked, onCheckedChange = null)<br>        Spacer(Modifier.size(6.dp))<br>        Text(label)<br>    }<br>}</pre><p>The method basically doesn’t use the <strong><em>checkchange </em></strong>of the checkbox itself as it forces the user to select the checkbox and the text will not be considered in the check. That’s why we forced the checkchange in the Row that hosts the checkbox and the label inside a Text composable.</p><p>After updating the <strong><em>LoginForm()</em></strong> method, it should look like this :</p><pre>@Composable<br>fun LoginForm() {<br>    Surface {<br>        Column(<br>            verticalArrangement = Arrangement.Center,<br>            horizontalAlignment = Alignment.CenterHorizontally,<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .padding(horizontal = 30.dp)<br>        ) {<br>            LoginField(<br>                value = &quot;login&quot;,<br>                onChange = { },<br>                modifier = Modifier.fillMaxWidth()<br>            )<br>            PasswordField(<br>                value = &quot;password&quot;,<br>                onChange = { },<br>                submit = { },<br>                modifier = Modifier.fillMaxWidth()<br>            )<br>            Spacer(modifier = Modifier.height(10.dp))<br>            LabeledCheckbox(<br>                label = &quot;Remember Me&quot;,<br>                onCheckChanged = { },<br>                isChecked = false<br>            )<br>        }<br>    }<br>}</pre><p>The last thing to add to the view is the Button and we can add it directly to the <strong><em>LoginForm()</em></strong> method as follows:</p><pre>@Composable<br>fun LoginForm() {<br>    Surface {<br>        Column(<br>            verticalArrangement = Arrangement.Center,<br>            horizontalAlignment = Alignment.CenterHorizontally,<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .padding(horizontal = 30.dp)<br>        ) {<br>            LoginField(<br>                value = &quot;login&quot;,<br>                onChange = { },<br>                modifier = Modifier.fillMaxWidth()<br>            )<br>            PasswordField(<br>                value = &quot;password&quot;,<br>                onChange = { },<br>                submit = { },<br>                modifier = Modifier.fillMaxWidth()<br>            )<br>            Spacer(modifier = Modifier.height(10.dp))<br>            LabeledCheckbox(<br>                label = &quot;Remember Me&quot;,<br>                onCheckChanged = { },<br>                isChecked = false<br>            )<br>            Button(<br>                onClick = { },<br>                enabled = true,<br>                shape = RoundedCornerShape(5.dp),<br>                modifier = Modifier.fillMaxWidth()<br>            ) {<br>                Text(&quot;Login&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>Let’s add some logic now to store the data from the form and use it to submit the form and check the credentials. First, let’s add a data class:</p><pre>data class Credentials(<br>    var login: String = &quot;&quot;,<br>    var pwd: String = &quot;&quot;,<br>    var remember: Boolean = false<br>) {<br>    fun isNotEmpty(): Boolean {<br>        return login.isNotEmpty() &amp;&amp; pwd.isNotEmpty()<br>    }<br>}</pre><p>Then, let’s define a method <strong><em>checkCredentials()</em></strong> that should check the credentials and then allow the user to navigate to the <strong><em>MainActivity </em></strong>view. Here, the condition is just not to be empty and the login to be admin:</p><pre>fun checkCredentials(creds: Credentials, context: Context): Boolean {<br>    if (creds.isNotEmpty() &amp;&amp; creds.login == &quot;admin&quot;) {<br>        context.startActivity(Intent(context, MainActivity::class.java))<br>        (context as Activity).finish()<br>        return true<br>    } else {<br>        Toast.makeText(context, &quot;Wrong Credentials&quot;, Toast.LENGTH_SHORT).show()<br>        return false<br>    }<br>}</pre><p>notice that we need a context for this method, so we’ll have to pass it as a parameter as well as have a credentials variable of type Credentials in our <strong><em>LoginPage</em></strong>. Let’s make those changes by adding to variables :</p><pre>var credentials by remember { mutableStateOf(Credentials()) }<br>val context = LocalContext.current</pre><p>If you’re struggling with the imports, here they are :</p><pre>import androidx.compose.runtime.getValue<br>import androidx.compose.runtime.mutableStateOf<br>import androidx.compose.runtime.remember<br>import androidx.compose.runtime.setValue</pre><p>Now let’s update our<strong><em> LoginPage()</em></strong> method to add the value of the Fields, setup the change methods and configure the submit method</p><pre>@Composable<br>fun LoginForm() {<br>    Surface {<br>        var credentials by remember { mutableStateOf(Credentials()) }<br>        val context = LocalContext.current<br><br>        Column(<br>            verticalArrangement = Arrangement.Center,<br>            horizontalAlignment = Alignment.CenterHorizontally,<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .padding(horizontal = 30.dp)<br>        ) {<br>            LoginField(<br>                value = credentials.login,<br>                onChange = { data -&gt; credentials = credentials.copy(login = data) },<br>                modifier = Modifier.fillMaxWidth()<br>            )<br>            PasswordField(<br>                value = credentials.pwd,<br>                onChange = { data -&gt; credentials = credentials.copy(pwd = data) },<br>                submit = {<br>                    if (!checkCredentials(credentials, context)) credentials = Credentials()<br>                },<br>                modifier = Modifier.fillMaxWidth()<br>            )<br>            Spacer(modifier = Modifier.height(10.dp))<br>            LabeledCheckbox(<br>                label = &quot;Remember Me&quot;,<br>                onCheckChanged = {<br>                    credentials = credentials.copy(remember = !credentials.remember)<br>                },<br>                isChecked = credentials.remember<br>            )<br>            Spacer(modifier = Modifier.height(20.dp))<br>            Button(<br>                onClick = {<br>                    if (!checkCredentials(credentials, context)) credentials = Credentials()<br>                },<br>                enabled = credentials.isNotEmpty(),<br>                shape = RoundedCornerShape(5.dp),<br>                modifier = Modifier.fillMaxWidth()<br>            ) {<br>                Text(&quot;Login&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>In this code, if the credentials don’t match, the fields will be emptied. We used a copy of the credentials because it’s an object and if we only change the variables inside, Compose will not detect it because the object itself didn’t change. So we’re creating a copy and we’re changing the element that changed.</p><p>And we’re done! You can run your application to see how that looks like.</p><p>The GitHub code can be found here : <a href="https://github.com/Anass-ABEA/JetPack-Compose-Login-UI">GitHub repo</a></p><p>Here’s a YouTube video if you want to follow the same steps more visually :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Ft5O3omAI-6c%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dt5O3omAI-6c&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Ft5O3omAI-6c%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bbbb68f47454730c448e1e8bea6fc0d/href">https://medium.com/media/1bbbb68f47454730c448e1e8bea6fc0d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c92af690234" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>