<?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 Ahmed Samir on Medium]]></title>
        <description><![CDATA[Stories by Ahmed Samir on Medium]]></description>
        <link>https://medium.com/@astroa7m?source=rss-599d4d89d641------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UrndXJ9pWQhYBltZEhxBgw.jpeg</url>
            <title>Stories by Ahmed Samir on Medium</title>
            <link>https://medium.com/@astroa7m?source=rss-599d4d89d641------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 21:31:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@astroa7m/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[Converting CSV Files for RAG Systems: A Concise Guide]]></title>
            <link>https://astroa7m.medium.com/converting-csv-files-for-rag-systems-a-concise-guide-856af3d8999a?source=rss-599d4d89d641------2</link>
            <guid isPermaLink="false">https://medium.com/p/856af3d8999a</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Ahmed Samir]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 11:37:54 GMT</pubDate>
            <atom:updated>2025-04-05T11:37:54.118Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Retrieval-Augmented Generation (RAG) systems enhance Large Language Models (LLMs) by providing them with external knowledge. Converting CSV files into formats suitable for RAG systems is crucial for organizations with tabular data who want to leverage these powerful AI capabilities.</p><h3>Best Approaches for CSV to RAG Conversion</h3><h3>1. Direct Vector Embedding Approach</h3><ul><li>Process: Convert CSV rows/columns → Text chunks → Vector embeddings → Vector database</li><li>Best for: Smaller datasets with clear semantic meaning</li><li>Tools: LangChain&#39;s CSVLoader, LlamaIndex&#39;s CSVNodeParser</li><li>Advantage: Simplest implementation with minimal preprocessing</li></ul><h3>2. CSV to JSON Conversion</h3><ul><li>Process: CSV → JSON → Text chunks → Vector embeddings → Vector database</li><li>Best for: Complex CSV structures with nested relationships</li><li>Tools: Pandas for conversion, any RAG framework for processing</li><li>Advantage: Better preservation of data relationships and structure</li></ul><h3>3. Structured Query Approach</h3><ul><li>Process: CSV → Pandas DataFrame → LLM-generated SQL-like queries → Results to LLM</li><li>Best for: Analytical questions requiring precise data manipulation</li><li>Tools: Pandas, LangChain agents</li><li>Advantage: Maintains data integrity, excellent for numerical analysis</li></ul><h3>4. Hybrid Chunking Strategy</h3><ul><li>Process: CSV → Multiple chunking strategies → Combined vector database</li><li>Best for: Complex datasets with varied query patterns</li><li>Tools: LlamaIndex, Haystack</li><li>Advantage: Balances between semantic search and structured data integrity</li></ul><h3>5. Summarization-First Approach</h3><ul><li>Process: CSV → LLM summarization → Vector embeddings of summaries → Original data retrieval</li><li>Best for: Very large CSV files with clear thematic sections</li><li>Tools: Any LLM for summarization, vector database for storage</li><li>Advantage: Reduces storage requirements while maintaining context</li></ul><h3>Key Best Practices</h3><ol><li>Preserve Context: Maintain column headers and relationships in chunks</li><li>Optimize Chunk Size: Balance between context preservation and token limits</li><li>Enrich with Metadata: Store column names and data types as metadata</li><li>Implement Hybrid Search: Combine keyword and semantic search for better results</li><li>Preprocess Effectively: Clean, normalize, and structure data before conversion</li></ol><h3>Recommended Tools:</h3><p>1- <strong>LangChain (</strong>l<a href="https://www.langchain.com/">angchain.com</a>)<strong>:</strong> Built-in CSV loaders, comprehensive RAG framework</p><p>2- <strong>LlamaIndex (</strong><a href="https://www.llamaindex.ai/">llamaindex.ai</a><strong>): </strong>Specialized CSV parsing, multiple indexing strategies</p><p>3- <strong>Pandas (</strong><a href="https://pandas.pydata.org/">pandas.pydata.org</a>): Industry-standard CSV manipulation</p><p>4- <strong>Chroma DB (</strong><a href="https://www.trychroma.com/">trychroma.com</a>): Simple vector database with good CSV integration</p><p>5- <strong>Haystack </strong>(<a href="https://haystack.deepset.ai/">haystack.deepset.ai</a>): Flexible pipelines for CSV processing</p><h3>Implementation Example</h3><pre># Basic CSV to RAG implementation using LangChain<br>from langchain.document_loaders import CSVLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.embeddings import OpenAIEmbeddings<br>from langchain.vectorstores import Chroma<br><br># 1. Load CSV file<br>loader = CSVLoader(file_path=&quot;data.csv&quot;, csv_args={&#39;delimiter&#39;: &#39;,&#39;})<br>documents = loader.load()<br><br># 2. Split into chunks<br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)<br>chunks = text_splitter.split_documents(documents)<br><br># 3. Create embeddings and store in vector database<br>embeddings = OpenAIEmbeddings()<br>vectorstore = Chroma.from_documents(chunks, embeddings)<br><br># 4. Create retriever for RAG<br>retriever = vectorstore.as_retriever(search_kwargs={&quot;k&quot;: 5})<br><br># 5. Use in RAG pipeline<br># ... connect to your LLM of choice</pre><h3>Conclusion</h3><p>The best approach for converting CSV files for RAG systems depends on your specific data characteristics and query patterns. For most use cases, a combination of proper chunking strategies, metadata enrichment, and the right vector database will yield optimal results. Start with simpler approaches and iterate based on performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=856af3d8999a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Can Any Programming Language Be More Environmentally Friendly, Especially Kotlin?]]></title>
            <link>https://astroa7m.medium.com/how-can-any-programming-language-be-more-environmentally-friendly-especially-kotlin-820bd3fabe7b?source=rss-599d4d89d641------2</link>
            <guid isPermaLink="false">https://medium.com/p/820bd3fabe7b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[environment]]></category>
            <category><![CDATA[energy-efficiency]]></category>
            <category><![CDATA[kmm]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Ahmed Samir]]></dc:creator>
            <pubDate>Fri, 23 Dec 2022 12:08:59 GMT</pubDate>
            <atom:updated>2022-12-23T12:32:21.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RAJ-NofCS7jluizj" /><figcaption>Photo by <a href="https://unsplash.com/@federize?utm_source=medium&amp;utm_medium=referral">Federico Beccari</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Kotlin as a programming language has a moderate effect on the environment, as <strong>it is not naturally environmentally friendly or harmful</strong>. In general, how a particular programming language can possibly affect the environment depends on the approaches and the usage of the language, and the resources it consumes in addition to the systems it was involved in its development process. However, Kotlin has been designed to be more concise and expressive than other programming languages, as writing code in Kotlin is more <strong>efficient and requires fewer resources</strong>. Below, are some ways and examples to show how we can use Kotlin in a manner that is related to environment conservation.</p><p>Kotlin has multiplatform capabilities like Kotlin Multiplatform (<strong>KMP</strong>) which refers to Kotlin’s ability to build cross-platform systems among desktop, web, and mobile, and Kotlin Multiplatform Mobile (<strong>KMM</strong>) that allows the developer to create mobile applications on Android and IOS by <strong>sharing a big portion of the codebase</strong> and finally this code base is <strong>compiled natively to Swift</strong> (IOS programming language). It was found that <strong>KMM can potentially provide nearly the same performance as a native app on both platforms</strong> according to a survey conducted by JetBrains (the creators of Kotlin programming language) about KMM [1]. Furthermore, JetBrains has been continuously improving KMM technology in terms of performance and energy consumption, as they have released a <strong>new memory manager</strong> [2] that works for Kotlin Native which is used for cross-platform development. Plenty of companies are satisfied with KMM as a cross-platform solution [3], most notably the famous <strong>cloud provider VMware and Memrise</strong> which has a language learning app holding the same name. VMware and Memrise found that cross-platform frameworks like <strong>React Native and Flutter</strong> did not fit with their requirements and needs. Finally, they chose Kotlin as the beneficial solution for their products [4][5]. With the help of KMM, Kotlin could be <strong>environmentally friendly</strong> as it can help reduce the energy consumption associated with running separate systems for each platform as well as optimize the app’s performance, usage of resources, and hardware accessibility.</p><p>Another way to make software development more environmentally friendly, is to <strong>design systems that use resources and energy efficiently</strong>, which can be achieved by focusing on efficient and well-designed systems, we can minimize resource usage and energy consumption, ultimately making a positive impact on the environment and <strong>reducing individuals carbon footprint</strong>. Along with efficiency, mostly any programming language can be used to build environmentally friendly systems, such as <strong>carpooling and public transit systems</strong> to significantly reduce the possible emission of carbon. Additionally, developing software that helps organizations or individuals <strong>reduce the usage of energy and conserve resources</strong> by giving them tips and information and potentially tracking their usage of energy and resources. Additionally, helping <strong>farmers to reduce the use of synthetic materials</strong> by giving them natural replacements.</p><p>Finally, programming languages generally should be used with caution while building applications by applying <strong>efficient algorithms and using a corresponding data structure</strong> to reduce the time and memory usage of software, therefore reducing the overall energy consumption of the software system. Along with that choosing the right framework to complete a particular job and creating environmentally friendly software such as the ones mentioned.</p><h3>References</h3><p>[1] Petrova, E. (2021) Results of the Kotlin multiplatform survey Q1-Q2 2021: The kotlin blog, The JetBrains Blog. Available from &lt;https://blog.jetbrains.com/kotlin/2021/10/multiplatform-survey-q1-q2-2021/#Who_uses_KMM_and_why&gt; (20/12/2022).</p><p>[2] Petrova, E. (2021) Try the New Kotlin/Native Memory Manager Development Preview: The kotlin blog, The JetBrains Blog. Available from &lt; https://blog.jetbrains.com/kotlin/2021/08/try-the-new-kotlin-native-memory-manager-development-preview/#Why_do_we_need_a_new_memory_manager&gt; (20/12/2022).</p><p>[3] Case Study — Kotlin — URL: <a href="https://kotlinlang.org/lp/mobile/case-studies/">https://kotlinlang.org/lp/mobile/case-studies/</a></p><p>[4] Memrise — Kotlin — URL: <a href="https://kotlinlang.org/lp/mobile/case-studies/memrise">https://kotlinlang.org/lp/mobile/case-studies/memrise</a></p><p>[5] VMware — Kotlin — URL: <a href="https://kotlinlang.org/lp/mobile/case-studies/vmware/">https://kotlinlang.org/lp/mobile/case-studies/vmware/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=820bd3fabe7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handle Deep links For In-App Content In A Single Activity Compose Architecture]]></title>
            <link>https://astroa7m.medium.com/handle-deep-links-for-in-app-content-in-a-single-activity-compose-architecture-ecdf722da95c?source=rss-599d4d89d641------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecdf722da95c</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[compose-ui]]></category>
            <category><![CDATA[deep-linking]]></category>
            <category><![CDATA[deep-link-android]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Ahmed Samir]]></dc:creator>
            <pubDate>Tue, 25 Oct 2022 21:03:50 GMT</pubDate>
            <atom:updated>2022-10-25T21:03:50.148Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*L0pHqkNis-Jms3J01ykZfQ.jpeg" /><figcaption>Kaize boiz</figcaption></figure><p>Handling deep links can come a little bit tricky when handling it in <strong>a single activity Compose</strong> project especially when you are not used to them, as we only have one activity and multiple Compose functions. But if you think about it is the same as our beloved <strong>single-activity multiple-fragments</strong> architecture. We only defined one activity that holds our manifest file, and there is where our intent-filters belong. Additionally, starting from Android 12 (API 31) if your app holds a link (<strong>that has HTTP/HTTPS schemes), </strong>ends with a <strong>domain (such as .com, .net, etc), </strong>and is not verified or approved as your app URL, then the OS will automatically launch the intent within the device’s default browser.</p><p>The Android <a href="https://developer.android.com/training/app-links/verify-android-applinks">docs</a> have an easy-to-follow guide if you’re willing to make your domains verified across your apps, which are usually connected to the websites of your business and eventually land you in your in-app content even in Android 12. However, if you, for instance, create an application only for mobile or Android platforms and you don’t really tend to target the web platform currently by any chance or for instance you didn’t want to verify your URL for any cause, then handling them manually would suffice.</p><h3>Article’s content</h3><p>Well let’s discover what we’re going to discuss in this article</p><ol><li><a href="#b074"><strong>Project &amp; deep links setup</strong></a></li><li><a href="#6eb2"><strong>Deep-linking with multiple screens</strong></a></li><li><a href="#af5a"><strong>Handling the default behavior of deep links manually in Android 12 (API 31) and onwards</strong></a></li></ol><h4><strong>1. Project &amp; deep links setup</strong></h4><p>Let’s dive into setting up our project. If you want to follow along, clone this <a href="https://github.com/Astroa7m/Deep-links-medium-example/tree/initial"><strong>repository</strong></a> from the initial branch or switch to the final branch for the complete code.</p><blockquote>If you are following along with an emulator or a device that has Android 12 then testing within the app won’t work for you unless you apply the step mentioned in <a href="#af5a">Handling deep links in Android 12</a></blockquote><p>The starter project has everything to get you started, a couple of dependencies for navigation, Compose, and Room Database. Since we are going to learn about deep links only, we won’t go over the Room DB code, though you can take a look at the code at your leisure.</p><p>Our use case is very simple, we are going to have a prepopulated database. And we are going to use deep links to navigate to a particular item within the list. Similarly, you could use it with Retrofit to perform some network requests accordingly.</p><p>Now to setup up a deep link for our project, we have to add the <strong>intent-filter </strong>to our manifest file and make sure you place it within the &lt;activity&gt; tag body like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ff3b1ecc07b764667e09f5da1a967fa/href">https://medium.com/media/4ff3b1ecc07b764667e09f5da1a967fa/href</a></iframe><p>Our intent-filter consists of multiple elements, let’s look at each in brief detail according to the <a href="https://developer.android.com/training/app-links/deep-linking#adding-filters">docs</a>:</p><p><strong>&lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;: </strong>This allows your app to respond to implicit intents.</p><p><strong>&lt;category android:name=&quot;android.intent.category.BROWSABLE&quot;/&gt;: </strong>It is required for the intent filter to be accessible from a web browser. Without it, clicking a link in a browser cannot resolve to your app.</p><p><strong>&lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;: </strong>Specify the <a href="https://developer.android.com/reference/android/content/Intent#ACTION_VIEW">ACTION_VIEW</a> intent action so that the intent filter can be reached from Google Search.</p><p><strong>&lt;data …&gt;: </strong>defines your URL elements in the format (scheme://host/path). Note that the path has other variants which you could look at in the docs linked above. The scheme element can be anything rather than <strong>HTTP/HTTPS </strong>if you’re not supporting the web. However, we used HTTPS intentionally for this use case, so we see how we fail to resolve to activity with Android 12 &amp; onwards.</p><p>Wait, what? we said that we will verify our links manually, then why did we use <strong>category.BROWSABLE</strong> &amp; <strong>action.VIEW</strong>? Well, they might seem redundant to have but they’re crucial elements that will help in the verification/association step in <a href="#af5a">Handling deep links in Android 12</a>.</p><p>if you test the deep link with the command line it would open your current state of the activity, which is currently empty. Let’s create our navigation graph and screens to test it.</p><p><strong>In MainActivity.kt:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9f24925ebbac4be45ada57ae3f18e1e/href">https://medium.com/media/b9f24925ebbac4be45ada57ae3f18e1e/href</a></iframe><p>What we implemented here is just:</p><ul><li>Two screens <br>1- <strong>Home: </strong>showing a list of users coming from ViewModel. <br>2- <strong>Details: </strong>showing details of the currently viewed user</li><li>Added arguments to Destination.Details</li><li>Made Destination.Details handle a deep link that is similar to our URL defined in the Manifest file.</li></ul><p>Notice how once we are done with our <strong>uriPattern </strong>we had to start adding arguments “<strong>?userId={userId}</strong>”. And that’s because this deep link will be used to navigate to the details screen which by default takes an argument that we specified in “<strong>arguments = …</strong>”. Failing to do so, will cause a crash. Now the final Uri will be as:</p><p><a href="https://deeplinkapp.com/sharing-user?userId=the-id-of-the-user-you-clicked-on)"><strong>https://deeplinkapp.com/sharing-user?userId=the-id-of-the-user-you-clicked-on)</strong></a></p><p>And here’s the code for <strong>Destinations.kt</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc720a9547a7d26abe2f0b31ca52418f/href">https://medium.com/media/fc720a9547a7d26abe2f0b31ca52418f/href</a></iframe><p>Now write this command in your terminal passing a user id between 1–5:</p><pre>adb shell am start -W -a android.intent.action.VIEW -d &quot;<a href="https://deeplinkapp.com/sharing-user?userId=2">https://deeplinkapp.com/sharing-user?userId=1</a>&quot;</pre><p>Before it used to launch our activity or our <strong>startDestination</strong> of our Navigation graph, but now it launches the destination that handles the deep link uri in the graph. Though trying to test “https://deeplinkapp.com/sharing-user” only or with other arguments that are not specified, then it would still launch your activity as there is no composable that handles this specific URI alone.</p><p>Now the approach of getting the user is not very preferable:</p><pre>val  user = users.<em>find </em><strong>{ it</strong>.id == userId <strong>}</strong></pre><p>And that’s because of two reasons:</p><ul><li>the user initially would be null because of the nature of <strong>Compose infrastructure</strong></li><li>We are getting the user from the currently displayed list</li></ul><p>What if the data received from DB is paginated which means not all users are loaded locally unless we scroll, or for instance, we didn’t have the data in our DB and would rather make a network request? Or maybe you have some condition that tells the detail screen how to behave when the item is null. In our code, we show a dialog to ask the user if they want to add this unfound user. So, with this approach the dialog shows for a couple of milliseconds even if the user is found which is kind of bothersome.</p><p>Now change your implementation to the following within the composable of details destination</p><pre>// details screen<br><em>composable</em>(<br>    route = Destinations.Details.route,<br>    deepLinks = <em>listOf</em>(<br>        <em>navDeepLink </em><strong>{<br>            </strong>val c = this@MainActivity<br>            val scheme = c.getString(R.string.<em>scheme</em>)<br>            val host = c.getString(R.string.<em>host</em>)<br>            val path = c.getString(R.string.<em>path_to_existed_user</em>)<br>            val uri = &quot;$scheme://$host$path?userId={userId}&quot;<br>            uriPattern = uri<br>        <strong>}<br>    </strong>),<br>    arguments = <em>listOf</em>(<br>        <em>navArgument</em>(&quot;userId&quot;) <strong>{<br>            </strong>this.type = NavType.IntType<br>        <strong>}<br>    </strong>)<br>) <strong>{ </strong>navBackStackEntry <strong>-&gt;<br>    </strong>var user: User? by <em>remember </em><strong>{ </strong><em>mutableStateOf</em>(null) <strong>}<br>    </strong>var showDetailsScreen by <em>remember </em><strong>{ </strong><em>mutableStateOf</em>(false) <strong>}<br>    </strong><em>LaunchedEffect</em>(key1 = Unit) <strong>{<br>        </strong>val userId = navBackStackEntry.arguments?.getInt(&quot;userId&quot;)<br>        user = viewModel.getUser(userId)<br>        showDetailsScreen = true<br>    <strong>}<br>    </strong>if (showDetailsScreen){<br>        <em>DetailsScreen</em>(<br>            user = user,<br>            onDismiss = <strong>{ </strong>navController.popBackStack() <strong>}</strong>,<br>            onAddNewUserClicked = <strong>{<br><br>            }</strong>,<br>            onSharing = <strong>{<br><br>            }<br>        </strong>)<br>    }<br><strong>}</strong></pre><p>What this patch does, is just awaits the result of finding that id in our local DB. Then launches the screen whether the result is found or null. eventually, we granted control over the state of showing the adding-dialog.</p><h4><strong>2. Deep-linking with multiple screens</strong></h4><p>What happens when the item is null, and the user clicks the add on the add-dialog? We simply launch another screen. Beforehand, we should do some modifications to our code:</p><ul><li>Add the following class in the <strong>Destinations.kt:</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b306f32f342876fcdb2afc813e88381f/href">https://medium.com/media/b306f32f342876fcdb2afc813e88381f/href</a></iframe><ul><li>Add another <strong>&lt;data&gt; </strong>element in the same intent-filter in your manifest file like so:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e9f1c091f4df4c0632e9700c3599065/href">https://medium.com/media/5e9f1c091f4df4c0632e9700c3599065/href</a></iframe><p>Though you can create another &lt;intent-filter&gt; and add the same &lt;category&gt; and &lt;action&gt; elements then a different &lt;data&gt;, but since we use the same scheme and host we can leave our data here in the same &lt;intent-filter&gt; you can learn more about this <a href="https://developer.android.com/training/app-links/deep-linking#adding-filters">here</a>.</p><ul><li>And finally add the screen that should handle your new url:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04bb2d6ad63256e6e2cf9ea554fc1972/href">https://medium.com/media/04bb2d6ad63256e6e2cf9ea554fc1972/href</a></iframe><p>Notice how we are passing multiple arguments to our URL, though it is not mandatory to pass navigation arguments like we did before, but the inverse is true.</p><p>Now by default when we navigate to the add screen without any arguments passed our user will have default values, but once we try to navigate with arguments then these values are automatically inserted in our textfields. Before testing implement the callback of the dialog like the following so we launch the adding destination.</p><pre><em>DetailsScreen</em>(<br>    user = user,<br>    onDismiss = <strong>{<br>        </strong>// implement this<br>        navController.popBackStack()<br>    <strong>}</strong>,<br>    onAddNewUserClicked = <strong>{<br>        </strong>// and this<br>        navController.popBackStack()<br>        navController.navigate(Destinations.AddNewUser.route)<br>    <strong>}</strong>,<br>    onSharing = <strong>{<br><br>    }<br></strong>)</pre><p>So, if we try the following command after running and building.</p><pre>adb shell am start -W -a android.intent.action.VIEW -d &quot;<a href="https://deeplinkapp.com/sharing-user?userId=12">https://deeplinkapp.com/sharing-user?userId=12</a>&quot;</pre><p>Where userId=12 which does not exist, the dialog will show up. Clicking add on the dialog will take us to the adding-screen.</p><p>You could also pass the URI string to <strong>navigate </strong>function<strong> </strong>which will have the same result.</p><p>Now for a trivial example yet important use case, say you’re sharing a link to add resource to the app, and this is where we are going to test the link of add-screen in the command line.</p><pre>adb shell am start -W -a android.intent.action.VIEW -d &quot;<a href="https://deeplinkapp.com/adding-user?name=some+name\&amp;desc=some+description\&amp;joinedYear=2022\&amp;isElite=true">https://deeplinkapp.com/adding-user?name=some+name\&amp;desc=some+description\&amp;joinedYear=2022\&amp;isElite=true</a>&quot;</pre><p>The result would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*_AsuYi-aqiScNMCErP-PQQ.png" /></figure><p>The screen got the values from the deep link applied them to the screen’s fields. Notice when we test using the command line we have to escape the ‘&amp;’ symbol by adding a backslash ‘\’.</p><p>What is left is to enable sharing so we can test our deep links in our emulator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55721915aeef6bb23af4b87889ba20c6/href">https://medium.com/media/55721915aeef6bb23af4b87889ba20c6/href</a></iframe><p>I made this helping singleton class to help us create and share our URLs. Now let’s implement <strong>onSharing </strong>callback in our DetailsScreen:</p><pre><em>DetailsScreen</em>(<br>    user = user,<br>    onDismiss = <strong>{ </strong>navController.popBackStack() <strong>}</strong>,<br>    onAddNewUserClicked = <strong>{<br>        </strong>navController.popBackStack()<br>        navController.navigate(Destinations.AddNewUser.route)<br>    <strong>}</strong>,<br>    onSharing = <strong>{<br>        </strong>// add this<br>        user?.<em>let</em><strong>{ </strong>nonNullableUser <strong>-&gt;<br>            </strong>SharingUtil.shareUserUrl(this@MainActivity, nonNullableUser)<br>        <strong>}<br>    }<br></strong>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*WGIEfLZTDxPTgkhCP5h06w.png" /><figcaption>link shared in the messages app</figcaption></figure><p>Now, clicking the share icon in our <strong>DetailsScreen</strong> will generate the link, and clicking the link after sharing it will resolve to that particular user in your app.</p><h4><strong>3. Handling the default behavior of deep links manually in Android 12 (API 31) and onwards</strong></h4><p>According to the note mentioned <a href="https://developer.android.com/training/app-links/deep-linking">here</a>, links must be first approved first to resolve to your app content, or it will launch the web browser as the default link handler. One of the ways mentioned to solve this issue is to request the user to associate the domain with our app. As we said before if you don’t want to go through all the hassle to verify that your app holds the domain etc. Then we would let the user verify the link at runtime.</p><p>I have made a helper function that checks if the link is selected and associated with our app as it will later launch an intent to let the user verify it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82acc976bd91948956649dd61d4f38d3/href">https://medium.com/media/82acc976bd91948956649dd61d4f38d3/href</a></iframe><p>By using the <strong>DomainVerificationManager </strong>we could check the current state of our domain which is unapproved by default in Android 12 &amp; later. So, after getting the domain state related to our app we check if the user has selected our app to be the default handler for our domains, as well as if the user has disabled link handling in the settings for our app.</p><p>if either of these conditions is met, then we launch the dialog telling the user why we need our app to be associated with our domain with additional instructions, so we don’t leave him/her in a daze.</p><p>By default, we are calling this function in the <strong>DetailsScreen </strong>composable, so the user will see the dialog once he/she clicks on a list’s item</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfb0461afbceb2e83bee22fb4494b812/href">https://medium.com/media/dfb0461afbceb2e83bee22fb4494b812/href</a></iframe><p>Now let’s test and run the app on Android 12 or later:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cFNFHX86D3xo2XMqwKCvYw.png" /></figure><p>The dialog shows up, user clicks on open settings, then enables “open supported links”, and adds supported links, and finally, if we ever clicked a link shared from our app or tried to test the link with the command line, it will resolve to our activity.</p><p>Whenever the user disables “open supported links” or remove our link from the supported link the dialog will show up again the details screen, but the user can simply ignore it by clicking ignore.</p><p>Now remember when we said we needed <strong>category.BROWSABLE</strong> &amp; <strong>action.VIEW</strong>? Well, without them the “+ Add link” option wouldn’t be there so we wouldn’t be able to associate the app with our desired link.</p><p>Where am I using this approach? I used it in my last hobby project <a href="https://github.com/Astroa7m/Githuber"><strong>Githuber</strong></a></p><p><a href="https://github.com/Astroa7m/Githuber">GitHub - Astroa7m/Githuber: Material 3 Multi-Module Clean Architecture GitHub Android Client</a></p><p>Thank you for reading this far, if you have any concerns, please feel free to leave them in the comments, and if you liked the article don’t forget to give me a clap 👏🏻👏🏻👏🏻👏🏻👏🏻.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecdf722da95c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Schedule Image Displaying In Glance Widget With Work Manager API]]></title>
            <link>https://itnext.io/schedule-image-displaying-in-glance-widget-with-work-manager-api-cc474ed8571c?source=rss-599d4d89d641------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc474ed8571c</guid>
            <category><![CDATA[glance]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[workmanager]]></category>
            <category><![CDATA[widget]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Ahmed Samir]]></dc:creator>
            <pubDate>Thu, 30 Jun 2022 16:03:34 GMT</pubDate>
            <atom:updated>2022-07-01T16:15:18.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*puxM9pd6frlzR-nY8k96iw.jpeg" /></figure><p><strong>Glance </strong>accelerates the creation of application widgets for different surfaces such as home-screen, keyboards, etc. As it provides a handful of APIs to help us build the widget in <strong>Jetpack Compose style.</strong></p><h3>Prerequisites 🤔</h3><p>There are some concepts you need to at least be familiar with before reading this article.</p><ul><li><strong>Jetpack Compose</strong></li><li><strong>Preferences Datastore</strong></li><li><strong>Retrofit</strong></li><li><strong>ViewModels</strong></li><li><strong>WorkManager</strong></li></ul><h3>Project Setup 😃</h3><p>Now let’s start coding, create a new project and add the following dependencies in <strong>build.gradle</strong> (Module)</p><blockquote>Sidenote: The source code is available at the end of the article.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e88582e4a2193000bcec4224f67cc9e3/href">https://medium.com/media/e88582e4a2193000bcec4224f67cc9e3/href</a></iframe><p>And before we forget, add internet permission in the AndroidManifest.xml file.</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</pre><p>First, we will create a simple widget to see how we could build one, then we will connect it with <strong>WorkManager </strong>to start scheduling.</p><p>To create a widget, we need to do the following:</p><ul><li>Create a class that inherits from <strong>GlanceAppWidget</strong></li><li>Create a receiver class that inherits from <strong>GlanceAppWidgetReceiver</strong></li><li>Register our receiver &amp; provide our widget meta-data.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c463241ea7ebae43fe98374a0f1e2226/href">https://medium.com/media/c463241ea7ebae43fe98374a0f1e2226/href</a></iframe><p>Once you implement <strong>GlanceAppWidget </strong>you will then need to override a composable function called <strong>Content</strong>, and there is where you write how your widget UI would look like. Here I am using the Image composable to display an image from the drawable resource. It is worth mentioning that most of the Jetpack compose-related code that we use within the <strong>Content </strong>composable is imported from <strong>androidx.glance</strong>. You could also notice that we use an <strong>ImageProvider</strong> for the image composable instead of a painter (<strong>painterResource</strong>) in normal composable functions, as well as the modifier, here we use a <strong>GlanceModifier </strong>instead of a normal compose modifier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21773d68fd0511451b4b65c62cb67192/href">https://medium.com/media/21773d68fd0511451b4b65c62cb67192/href</a></iframe><p>After creating your widget receiver, you will have to connect your receiver to the widget by implementing the property <strong>glanceAppWidget</strong>.</p><pre>&lt;receiver<br>    android:name=&quot;.extra.RemoteWidgetReceiver&quot;<br>    android:enabled=&quot;true&quot;<br>    android:exported=&quot;false&quot;&gt;<br><br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;android.appwidget.action.APPWIDGET_UPDATE&quot; /&gt;<br>    &lt;/intent-filter&gt;<br><br>    &lt;meta-data<br>        android:name=&quot;android.appwidget.provider&quot;<br>        android:resource=&quot;@xml/widget_provider&quot; /&gt;<br><br>&lt;/receiver&gt;</pre><p>And finally, in your AndoirdManifest.xml file within your <strong>application</strong> tag register your receiver and add the intent filter and meta-data for the widget.</p><p>Though our widget is written in compose, we need to create some files in XML, things like how the widget would look initially and some attributes and configurations related to the widget. All these configurations are stored in <strong>widget_provider.xml</strong> file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a82ce01de351e1b581da21a6a949fff3/href">https://medium.com/media/a82ce01de351e1b581da21a6a949fff3/href</a></iframe><p>As you can see in widget_provider.xml we define some information about our widget. Before we explain some of these attributes, here is the code for the <strong>widget_initial_layout.xml</strong> file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9be38eaf50e92d779a3397eb110a008d/href">https://medium.com/media/9be38eaf50e92d779a3397eb110a008d/href</a></iframe><p>In the following figures, we see how some of these attributes are used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*N1Vi5HTZKng38LLQsaOy2A.jpeg" /><figcaption>figure 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVVfiQfCEJeiA_BDDyqlPg.jpeg" /><figcaption>figure 2</figcaption></figure><p>You can also take a look at all the possible attributes for the appwidget-provider <a href="https://developer.android.com/guide/topics/appwidgets">here</a>. Now let’s run the app and see our result so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*MfbqZDtBJuqUJJaj3oPaWw.gif" /></figure><p>After knowing how we can set up our widget, it is time to learn how we can schedule images for the widget. It is worth mentioning though that glance widget uses <strong>Preferences Datastore</strong> to persist data.</p><p>All we gonna do is that we gonna let the user choose a category, and upon this choice, we are going to get a random image every 15 minutes and display it in the widget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7Hi-BDw-5ztvh7dO879oQ.jpeg" /><figcaption>scheduling process</figcaption></figure><p>Now let’s start writing our program from the bottom of the hierarchy (data)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e5da010ed43384d0902617f7e3cc68d/href">https://medium.com/media/8e5da010ed43384d0902617f7e3cc68d/href</a></iframe><p>Two functions, one for fetching the image object and the other one for getting image raw bytes from the image object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cef2590ee509ea8a9ba311ccc7f023b/href">https://medium.com/media/8cef2590ee509ea8a9ba311ccc7f023b/href</a></iframe><p>Our preferences datastore class for getting and setting user category index into preferences.</p><p>Before checking out our Worker class, let’s see our <strong>MainScreenViewModel </strong>class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc443ba336391874779399edb8b039f3/href">https://medium.com/media/cc443ba336391874779399edb8b039f3/href</a></iframe><p>We monitor changes to our preferences on viewModel instantiation, and on each update, we call the <strong>setWork</strong> function to begin scheduling our RemoteImageWorker class to run every 15 minutes. Additionally, we set a restriction to our worker that the network is necessary in order to enqueue the worker. Finally, we pass initial data to the worker class as well, which is the index of the category from our preference.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9588eebe604c21e37c357dcd4c1126a2/href">https://medium.com/media/9588eebe604c21e37c357dcd4c1126a2/href</a></iframe><p>Too much going on innit? It’s completely the opposite, In glance, we don’t have rememberAsyncImagePainter from coil nor rememberGlidePainter from glide or any other libraries, so we have to handle the image url ourselves. In my approach, we get the <strong>inputData</strong> (category) that we passed from our view model. Then we query the API to get a random image object according to our category, and then we download that image from the <strong>regular</strong> property which holds a url to the image with a regular size. Finally, we write the image bytes into a file and clean up any previous images from any old scheduling. Once we are done with the process, we call the <strong>updateRemoteImageWidget</strong> function and pass the path of the image file to query every widget that descends from <strong>RemoteWidget </strong>and update the image file path in the widget preferences. Eventually, update every instance state of our widget which will make the widgets reload a new image file.</p><p>Now we should do some changes to our widget in order to reflect those updates from the worker</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23a8603d7be5bddeef889089a47593c2/href">https://medium.com/media/23a8603d7be5bddeef889089a47593c2/href</a></iframe><p>The <strong>currentState </strong>inline function allows us to retrieve the state that contains the data that we saved in the widget preferences. As we have already seen, glance widgets use the Preferences Datastore to persist data. As a result, every modification to <strong>filePathString </strong>that we submit from the worker class will result in a <strong>recomposition </strong>of our widget with the new path and a fresh image.</p><p>All the code you see in the <strong>Content </strong>function is executed once you select the widget and begin to dragging it. So all the update functionality in our worker class is only applied to a widget that is attached to a surface. But what happens if we run the application for the first time when we don’t have any widgets? Well, the image gets downloaded yes, but the <strong>filePathString </strong>is empty because the datastore file of a widget is produced only when the widget is created. Therefore, I made a simple function to retrieve a bitmap from a file path, and if the file path is empty (which will only happen the first time we add a widget) we load the jpg file from fileDir.</p><p>On every creation of an instance of the same widget, an new datastore file is created. So imagine if we have a widget then we try to add a new one, the first one will get the image but the second won’t. For that, we created <strong>CustomGlanceStateDefinition </strong>to pass the same datastore file to every instance of the widget. The code of the <strong>CustomGlanceStateDefinition</strong> is probably a boilerplate, so you’d always have the same code when you want to pass the same datastore file to every widget. Just don’t forget to override <strong>stateDefinition </strong>property and pass your <strong>CustomGlanceStateDefinition.</strong></p><p>Finally, you could see in <strong>GlanceAppWidget </strong>constructor it takes an optional parameter, XML layout for the error state of the widget which will appear whenever an error occurs while setting up the widget.</p><p>Now let’s take a <strong>glance </strong>at our result (got it? 😁). Widget Image is changed every 15 mins according to our category, or once we change the category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*9axQ4d71IS_LiCWQaUxswA.gif" /><figcaption>final result</figcaption></figure><p>That’s all for this article, here is the full <a href="https://github.com/Astroa7m/RemoteWidget">source code</a>. If you liked it don’t forget to give a star⭐ to the repository and a clap 👏🏻 for this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc474ed8571c" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/schedule-image-displaying-in-glance-widget-with-work-manager-api-cc474ed8571c">Schedule Image Displaying In Glance Widget With Work Manager API</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collapsible App Bar With MotionLayout in Jetpack Compose]]></title>
            <link>https://itnext.io/collapsible-app-bar-with-motionlayout-in-jetpack-compose-1fb2502acacc?source=rss-599d4d89d641------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fb2502acacc</guid>
            <category><![CDATA[appbar]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[motionlayout]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ahmed Samir]]></dc:creator>
            <pubDate>Thu, 09 Jun 2022 14:34:12 GMT</pubDate>
            <atom:updated>2022-06-10T14:45:48.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESkUEbFkVntTBcEJHpSadA.png" /></figure><p>We have seen how we could create collapsing app bars/toolbars with the view system before, using the <strong>AppBarLayout </strong>&amp; <strong>CollapsingToolbarLayout</strong>. Now in Jetpack Compose, nearly everything is entirely customizable. Expanding and collapsing a toolbar can be achieved without the help of <strong>MotionLayout </strong>as making animations in Android has never been easier with Compose animation APIs. But, we want to animate multiple properties/attributes of a view or a composable depending on the keyframes of an animation, or we might want to have a complex animation. Therefore, <strong>MotionLayout </strong>comes to the rescue as it simplifies the process by defining <strong>ConstraintSets</strong> that tell how the layout/UI would look at the start of the animation and how it would like at the end of it, and simply <strong>MotionLayout </strong>will animate through those sets.</p><p>Let’s start by adding our dependencies, or actually our single dependency</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a4817948d5c6b074ac8ff9b0f785ffc/href">https://medium.com/media/1a4817948d5c6b074ac8ff9b0f785ffc/href</a></iframe><p>In the view system, motion layout is a subclass of constraint layout, which makes sense why we are using constraint layout dependency here.</p><p>Now let’s move to define our constraints sets. unlike defining them with XML in the view system, motion layout in compos uses <a href="https://github.com/androidx/constraintlayout/wiki/Compose-MotionLayout-JSON-Syntax">JSON5 </a>syntax which is pretty similar to JSON. Create a new json5 file by placing it into your raw files under res. if you don’t have a raw file create one by right click on app&gt;New&gt;Android Resource Directory and under resource type choose raw. Finally, create a file named motion_scene.json5 file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc8aa97f512ca5596a84f9e8d4f56bd9/href">https://medium.com/media/cc8aa97f512ca5596a84f9e8d4f56bd9/href</a></iframe><p>Just like JSON, we start an object and then we define another ConstraintSets object where we place our sets of the layout. Notice here how we didn’t add quotations between the keys names as JSON5 doesn’t require us to do so.</p><p>Within each set (start &amp; end) we add our children views as objects then we start giving them attributes and constraints just like constraint layout and motion layout.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e8914d02604160da7a9b9ac2c556454/href">https://medium.com/media/3e8914d02604160da7a9b9ac2c556454/href</a></iframe><p>Here we defined how each and every view would look like at the start phase of our animation. each object’s name represents the ID of that view (e.g. user_name. box_image, etc.) which we gonna later use in our compose project. Width and height attributes are self-explanatory and their values are considered as Dp. Passing ‘spread’ as a value to width or height keys is equivalent to 0dp or match constraints in the view system. Now to give constraints to our objects or views, we would use top, bottom, start, and end attributes. As you can see the weapon_icon is constrained from the start of it to the start of the parent, the end of it to the end of the parent, and finally the bottom of it to the top of the user_image with an 8dp margin.</p><p>So defining constraints is like defining a list. First, you give the name of the list which points to the direction of where you want to constrain the current view (top, start, bottom, or end), then the target view to constrain the object to, and finally the direction of the target view to be constrained to. And the last argument is optional and it is where you would add some margin to the current view from the target view.</p><p>We have also defined an alpha for box_image which is a known attribute in the view system. But what is custom? We have a custom key as an object placed within the box object and this is how we would define a custom attribute to our view in motion layout in compose. It is equivalent to the <strong>CustomAttribute</strong> tag in old view world.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c80ae8db5d3bc5d6049b8f536a099483/href">https://medium.com/media/c80ae8db5d3bc5d6049b8f536a099483/href</a></iframe><p>After Completing the start phase of our animation, it’s time to declare the final look of it. Now within the end set let’s place our same views but with different values for their attributes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa727ddc5715835517b7ec32e8b8bd8c/href">https://medium.com/media/aa727ddc5715835517b7ec32e8b8bd8c/href</a></iframe><p>Pretty much the same process, the same IDs, and the same attributes. You could notice that we changed some values, for example, the alpha of the box_image was 1 in the start set and now it’s 0 in the end set. Similarly, the roundValue is now 0 for the box after making it 25 as well as the width and height for other views.</p><p>Now motion layout will do its best to transition from start to end sets. Before adding any custom transition, let’s see our result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c906423b63fff9b30b914873fb7b9ff6/href">https://medium.com/media/c906423b63fff9b30b914873fb7b9ff6/href</a></iframe><p>So within MotionAppBar composable, we access our motion scene file from raw resources then we define our progress variable, which we gonna use to transition from start to end depending on a float value coerced in-between 0 and 1. We want the animation to start if our first visible item of a list in lazyColumn is not the first, second, third, or fourth item. We also defined motionHeight for the MotionLayout composable to change accordingly during the animation to act as a top app bar. After fetching the motion scene we pass it to the MotionLayout composable along with the progress, and finally within the scope of motion layout we place our children composables and give them their IDs which we have already defined in the motion scene file by using the <strong>layoutId </strong>modifier and they will be placed according to our constraints. Now to make use of our custom attributes, we access them by <strong>motionProperties</strong> composable function and pass the ID of the view that we want to retrieve this custom property from. Lastly, we access this custom property by calling .value to get the value and .datatype to determine the type of the value of this custom property which is int in this case. So we call .int and pass the name of the attribute (roundValue).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95b91d55d9ff915ecd4945823709d2b0/href">https://medium.com/media/95b91d55d9ff915ecd4945823709d2b0/href</a></iframe><p>Let’s test this behavior in our <strong>MainActivity.kt </strong>file, we create a Scaffold composable to pass our MotionAppBar composable to the topBar argument. Notice the same lazy state is passed to the LazyColumn composable as well as our custom app bar to track the visibility of the first items. It’s also important to add <strong>animateContentSize() </strong>modifier to animate the the height of the lazy column once the height of the top app bar changes.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2FCIA730i%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D500&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2FCIA730i&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="500" height="1058" frameborder="0" scrolling="no"><a href="https://medium.com/media/9aa8992f32fd282c4d9986c6f4618c87/href">https://medium.com/media/9aa8992f32fd282c4d9986c6f4618c87/href</a></iframe><p>Pretty awesome right? Now let’s add our custom transition to make the app bar end state more elegant. Within the parent object, just underneath the <strong>ConstraintSets</strong> key in our motion_scene.json5 file we define our <strong>Transitions</strong> JSON object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ea03843fdf9a105162d22ea6f2f01f9/href">https://medium.com/media/1ea03843fdf9a105162d22ea6f2f01f9/href</a></iframe><p>Here under <strong>Transition, </strong>we define our default behavior for the animation. First, within the default object we construct our animation by adding where it should start from and to, and the arc path that our animation should take. The attribute <strong>pathMotionArc</strong> is set to transition through a vertical arc when the animation starts. Additionally, we describe how our views should animate their properties throughout the defined frames. For instance, under <strong>KeyFrames</strong> object we have a list of <strong>KeyAttributes </strong>objects<strong> </strong>and there is where we designate the properties values for each keyframe.</p><p>Let’s discuss the first one to make things clear. Firstly, the first object is targeting user_image view and there we set two frame 0 (beginning of the animation) and 100 (the end of the animation) and then follows the rotationZ attribute where we passed 0 and 360 degrees. That’s it, you have to do no more work, motion layout will take care of animating the rotation in the z-axis from 0 to 360. For the remaining objects, things are the same, just make sure that you pass an counterpart value for your attributes to every frame that you set.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2FXwO3LLN%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D500&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2FXwO3LLN&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="500" height="1058" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9265efcc1f92f58b116d5f5fc051bd8/href">https://medium.com/media/c9265efcc1f92f58b116d5f5fc051bd8/href</a></iframe><p>Here’s our final result and here’s the full <a href="https://github.com/Astroa7m/collapsible-app-bar"><strong>source code</strong></a>. I hope you enjoyed it and if you did, don’t forget to give a 👏.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fb2502acacc" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/collapsible-app-bar-with-motionlayout-in-jetpack-compose-1fb2502acacc">Collapsible App Bar With MotionLayout in Jetpack Compose</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WIFI QR Code Scanner With Camera X & Google ML Kit]]></title>
            <link>https://astroa7m.medium.com/wifi-qr-code-scanner-with-camera-x-google-ml-kit-5ad09ef5d3dc?source=rss-599d4d89d641------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ad09ef5d3dc</guid>
            <category><![CDATA[scanner]]></category>
            <category><![CDATA[cameras]]></category>
            <category><![CDATA[wifi]]></category>
            <category><![CDATA[qr-code]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ahmed Samir]]></dc:creator>
            <pubDate>Thu, 03 Mar 2022 02:09:56 GMT</pubDate>
            <atom:updated>2022-03-03T02:22:16.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tlQPtReTCrAOw37T6uK2w.png" /><figcaption>Free WIFI? Hurray!</figcaption></figure><p>You might have been to a restaurant or some public place before and found this paper hung on their walls or placed on tables. Well, so have I, when I was at the university last week I connected to their WIFI by scanning the QR code and at that moment I got an idea to implement this feature in an existing app.<br>You may wonder that we already have a third-party or OS apps that can handle this kind of process neatly with saving networks configuration and so (we are gonna discuss this later in the article), but doesn’t it itches you to know how would this functionality work somehow? It does itch me</p><p><strong>CameraX</strong></p><p>A Jetpack library that simplifies Camera driven apps development and supports different Android versions starting with <strong>Android 5.0 (API level 21)</strong> <a href="https://developer.android.com/training/camerax">see more</a>.</p><p><strong>ML Kit</strong></p><p>A machine learning mobile SDK that is maintained and developed by Google helps mobile developers to integrate machine learning into their apps. If you’ve ever used Mobile Vision API, you’ll be familiar with ML kit as Mobile Vision API has been deprecated and it’s now part of the ML SDK.</p><p>Alright, let’s start coding.</p><p>First with the dependencies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0a92eaf2d1aef27bbb30d683332eefd/href">https://medium.com/media/e0a92eaf2d1aef27bbb30d683332eefd/href</a></iframe><p>And since we’re using compose we are going to use<strong> </strong><a href="https://github.com/google/accompanist"><strong>Accompanist</strong></a><strong> </strong>library which simplifies commonly required tasks made with compose such as permissions requesting and handling in our case.</p><p>Do not worry if you’re using XML still, all that you’ll find here rather than UI and permissions handling is quite the same for XML so you’ll do okay with adding only CameraX &amp; ML kit dependencies.</p><p>Do not forget to add the permissions as well in <strong>AndroidManifest.xml</strong> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fd3787eb6d8a3b524c9cf5a2afed70c/href">https://medium.com/media/5fd3787eb6d8a3b524c9cf5a2afed70c/href</a></iframe><p>And now let’s start with the exciting stuff</p><p>So first we’re going to create <strong>QRCodeWIFiAnalyzer </strong>class that has the functionality to analyze QR codes images:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3197d7451f9dfa29b370109e585e7d6/href">https://medium.com/media/f3197d7451f9dfa29b370109e585e7d6/href</a></iframe><p>No! Don’t feel overwhelmed, it is easy once you get it, thanks to ML kit, implementing this is much easier than other libraries like Zxing Decoder.</p><p>Now, what’s happening? in the class constructor, we have 2 callbacks which are going to be invoked once we capture the result, or fail while doing so, and we implement Analyzer Interface from <strong>ImageAnalysis</strong> class which is considered as a UseCase for our Camera (we are going to see this later in the article) then we create a scanner object and specify the Barcode format that we want to use.</p><p><em>Note: You can skip specifying the Barcode format to make the scanner more flexible to scan different Barcode formats.</em></p><p>By implementing <strong>ImageAnalysis</strong> we got to override <strong>analyze</strong> function and there all the magic happens.</p><p>We first get the image captured from the camera preview by <strong>ImageProxy</strong> wrapper class <strong>image</strong> property, then we obtain <strong>ImageInput</strong> object from <strong>fromMediaImage</strong> function to pass it to the scanner to analyze it right after.</p><p>Now we check every barcode we got from the <strong>success listener</strong>. We’ll check its type, then get the SSID which resembles the access point or the WIFI name and the password, and once we’re done we send them to <strong>onSuccess lambda function</strong>. We could also put <strong>failure listener</strong> to catch exceptions regarding the scanning process and most importantly do not forget to close the image proxy in the <strong>complete listener</strong> to tell the analyzer that we are ready to analyze new images received from the camera.</p><p>Now let’s start handling the request for runtime permission for the camera. XML buddies, skip this step and do your usual handling as normal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6deda3bf036889e4a99b42b4a8184ba4/href">https://medium.com/media/6deda3bf036889e4a99b42b4a8184ba4/href</a></iframe><p>Here we are just making <strong>PermissionRequest</strong> composable with the parameter needed to request for a particular permission, then we make <strong>permissionState</strong> that observes permission results which we are going to use to handle them accordingly.</p><p>Then we make <strong>DisposableEffect</strong> to only request the permission when the Activity lifecycle is <strong>onStart</strong>. <strong>DisposableEffect</strong> is considered to be a <strong>Side-effect</strong> that gives you a controlled environment to run side-effect code that may interfere with the recomposition of a composable with giving respect to the lifecycle of composables. For more information take a look at side-effects <a href="https://developer.android.com/jetpack/compose/side-effects">here</a>.</p><p>Now in short, if the user accepted the permission then we call the content composables, and if he didn’t then we start showing the rational dialog composable to tell the user that this permission is essential for the app to function properly.</p><p>Discussing permissions handling with Accompanist library is behind the scope of this article, but if you want to learn more about it then click <a href="https://google.github.io/accompanist/permissions/">here</a>.</p><p>CameraX doesn’t have composables support yet, so we will convert the XML view by using <strong>AndroidView</strong> composable. For XML users again, you can stick to the &lt;<strong>PreviewView</strong>&gt; to learn more go through this rich cameraX <a href="https://developer.android.com/codelabs/camerax-getting-started#0">codelab</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16398363da8be2e6d8e2e75a0389ac8b/href">https://medium.com/media/16398363da8be2e6d8e2e75a0389ac8b/href</a></iframe><p>We first define the scale type used for our PreviewView to render, camera selector, to choose the preferable camera (front or back), and the same two lambda functions we used previously for our <strong>QRCodeWIFIAnalyzer</strong> class.</p><p>Start creating the PreviewView composable by creating an instance of <strong>PreviewView</strong> class and specifying its scale type and its layout parameters.</p><p>Next, we start making a <strong>previewUseCase</strong> object to build up our preview use case which will then be used to render previews from the camera and show it on the user screen, but before this, we should set a surface for it the be displayed on, so we get the <strong>surfaceProvider</strong> from the previously initialized preview view. By setting the previewUseCase surfaceProvider, the provider will tell the camera that previewUseCase is ready to get preview stream data to show it on screen.</p><p><strong>ImageAnalysis</strong> is another use case that we will use to make our app able to analyze the images received from the camera. So we’ll build our imageAnalysis object by setting the resolution, <strong>backpressureStrategy</strong> (which tells the camera what to do if it receives multiple images at once, and here we’re telling it to keep only the most received one), and finally our analyzer class.</p><p><strong>ProcessCameraProvider</strong> will help us bind the lifecycle of our camera to any <strong>LifecycleOwner</strong>, binding the lifecycle will determine when the camera should start &amp; stop according to the state of the lifecycle. So first we got to unbind all the owners in case if we will rebind them again when we for example rotate the screen. Rebinding again without unbinding will stop the data stream coming from the camera. Bind the camera using <strong>bindToLifecycle</strong> function and then pass the owner, cameraSelector, previewUseCase, imageAnalysis (AnalyzerUseCase) object.</p><p>So, now we’re done with the exciting stuff and we’ll dive into a brief introduction to 3 APIs to configure WIFI networks in Android.</p><h3>WifiConfiguration</h3><p><a href="https://developer.android.com/reference/android/net/wifi/WifiConfiguration"><strong>WifiConfiguration</strong></a> API can be used to configure a network, it was deprecated in Android API level 29 so it is no longer maintained but we are still going to use it for Android versions below 29.</p><h3>WifiNetworkSpecifier</h3><p>We can use this API to specify and request a WIFI network. Implementing this API is quite easy and similar to <strong>WifiConfiguration</strong> API. Although, it restricts the connection for the current app, meaning that once you leave the app, the connection is lost. As well as there will not be any internet connection unless you bind the network to the app process with ConnectivityManager API.</p><h3>WifiNetworkSuggestion</h3><p><a href="https://developer.android.com/reference/android/net/wifi/WifiNetworkSuggestion.html"><strong>WifiNetworkSuggestion</strong></a> API is used to provide WIFI networks suggestions or consideration and it proposes those networks to the user. It is considered to be the replacement for WifiConfiguration for Android 10 (API level 29) and above, though it lacks some options that we had in WifiConfiguration for security concerns. Nevertheless, we are going to use it as it binds the network and provides an internet connection automatically even after leaving the app, but the network will still be bounded to our app and once we delete the app the OS forgets our network, hence the network will not be saved.</p><p>Here we’re going to implement two functions that we’ll use to access a WIFI network. We could simply put those functions in a separate file to increase the readability and separate the concerns, but we’ll place them on <strong>MainActivity.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b561678f23b7e3a7405e70661a3fa78/href">https://medium.com/media/2b561678f23b7e3a7405e70661a3fa78/href</a></iframe><p><strong>connectBelow29 </strong>&amp; <strong>connect29AndAbove </strong>functions will be used to connect with Android API below 29, 29, or later respectively. Let’s start looking at <strong>connectBelow29</strong>, we first start checking if the WIFI is enabled through <strong>isWifiEnabled</strong> from <strong>WifiManager</strong> class and if so we proceed to connect to the network, else we enable the wifi. Once done, we create a <strong>WifiConfiguration </strong>object and set its SSID and pre-shared key, both surrounded by quotations. Additionally, we add the network to the <strong>WifiManager </strong>object by using <strong>addNetwork </strong>function which returns the network Id. Eventually, we disconnect the user from any network that he/she might be connected to, enable our desired network, and reconnect.</p><p>For Android Q (API 29) and above we use <strong>connect29AndAbove </strong>function, we also start checking the WIFI if it’s enabled, but if it is not, then we launch an Intent to let the user enable it by himself/herself in this case, as <strong>setWifiEnabled </strong>function is deprecated and won’t work for our Android Q devices. After that, we build our <strong>WifiNetworkSuggestion </strong>instance which is similar to building a WifiConfiguration object. Then, we remove the suggestion network from the <strong>WifiManager </strong>in case we were connected to it or connected to it via the app scanner and forgot it from the WIFI picker. We are almost done, all we got to do is to add the network suggestion back to the <strong>WifiManager</strong>, and additionally, we make and register a broadcast receiver which will be called once we connect to the network successfully.</p><p>Here’s the full code of the <strong>MainActivity:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1119bedae2d390b9da7d2d5aa64e10f0/href">https://medium.com/media/1119bedae2d390b9da7d2d5aa64e10f0/href</a></iframe><p>And yes before I forget here’s the function I used in MainActivity for checking the Android version:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ffc5c2bf0dec2d43e4a0fe4547b8a32/href">https://medium.com/media/5ffc5c2bf0dec2d43e4a0fe4547b8a32/href</a></iframe><p>Get the full project from <a href="https://github.com/Astroa7m/QR-WIFI-Connector">here</a></p><p>Connecting to a WIFI network with Android 29 and above programmatically is a headache and it is not ideal, even my solution here is not the perfect one. We all wish we could use <strong>WifiConfiguration</strong> which used to do the job seamlessly and made our life easier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ad09ef5d3dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>