<?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 Divyanshutw on Medium]]></title>
        <description><![CDATA[Stories by Divyanshutw on Medium]]></description>
        <link>https://medium.com/@divyanshutw?source=rss-82ab8498ce6c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3UCmvz6R7sBZFZdd</url>
            <title>Stories by Divyanshutw on Medium</title>
            <link>https://medium.com/@divyanshutw?source=rss-82ab8498ce6c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:21:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@divyanshutw/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[Configurable Feature Flags in Java:]]></title>
            <link>https://divyanshutw.medium.com/configurable-feature-flags-in-java-simplified-implementation-with-a-single-class-fd6058d3d34c?source=rss-82ab8498ce6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd6058d3d34c</guid>
            <category><![CDATA[feature-flags]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Divyanshutw]]></dc:creator>
            <pubDate>Tue, 07 May 2024 03:31:37 GMT</pubDate>
            <atom:updated>2024-05-07T04:49:21.492Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simplified Implementation with a Single Class</h4><h4>❗Problem statement:</h4><p>I want to run a logic at the backend and frontend that is based on an experiment. By experiment, I mean that there can be two different logics (say data science algorithms, etc.) and I want to run experiment 1 for a certain set of users and experiment 2 for the remaining set of users. This is called running A/B experiments in general or implementing feature flags.</p><p>It can also be understood as a beta program. For some users, the beta experiment will run and the remaining users will continue to see the older stable version.</p><p>Or there might be another scenario where the team is confused about 2 different data science algorithms or 2 different frontend designs. So they can ask us to run one algorithm for 50% of users and another algorithm for the remaining 50% of users. Note that there can be more than two sets of variations too.</p><blockquote>So the problem is to run K different experiments with N1,N2,N3,….Nk no. of logics respectively and the division percentage has to be configurable, i.e., anyone else can easily change the configurations of the traffic division. Also, the session of one user has to be sticky, i.e., if a user is viewing experiment A in a browser session, he should be shown the same experiment everytime in that session. Don’t blow your mind 🤯 reading the problem, I’ve got you covered.</blockquote><h4><strong>💡Idea:</strong></h4><p>Now the constraint here is to identify a particular user. I need to identify a user(or browser session) because if two experiments are going on: <em>A</em> and <em>B</em>, I want that in a particular session, if experiment <em>A</em> is being shown, then throughout the session experiment <em>A</em> should be shown. It shouldn’t happen that a user reloads his browser tab and he is seeing experiment B now. This is called a <strong>sticky session</strong> in general.</p><p>There can be several ways to identify a user. We can use the user’s IP or a unique transaction-id for example. In my case, I have used the timestamp when the session was first opened. If the timestamp cookie is not received in the header, it is set otherwise the timestamp cookie received in the request header is used. Whenever the user first opens his session, their timestamp is stored as a cookie in their browser session.</p><p>Based on this timestamp, I decide at runtime which experiments the user should be shown. This is done by simple probabilistic distribution. Next time, when the flow is executed in the same session, the same timestamp cookie is received and the probabilistic distribution would give the same experiment. This way, the sticky session is also maintained.</p><p>Now, let’s delve into the implementation details in the code.🧑‍💻</p><h4>✍️<strong>Low level design:</strong></h4><p>Here is the class diagram of the service depicting all important classes, models and entities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/0*3pfrDdaeM72twK9S" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/0*dGdbOETwzZVR3PvB" /></figure><p>Here are some details of the project:</p><p>🟡 Firstly there are simple CRUD APIs to create(/create), update(/updateExp) and get(/getExp) experiments and their respective configuration.</p><p>🟡 I have used simple h2 database for this example but it has to be replaced by the project’s mysql server configurations. Following properties have to be changed for this purpose:</p><pre>spring.datasource.url=jdbc:h2:file:~/data/divDB;DB_CLOSE_ON_EXIT=TRUE;DATABASE_TO_UPPER=true;IFEXISTS=FALSE<br>spring.datasource.driverClassName=org.h2.Driver<br>spring.datasource.username=user<br>spring.datasource.password=<br>spring.jpa.database-platform=org.hibernate.dialect.H2Dialect<br>spring.jpa.defer-datasource-initialization=true</pre><p>🟡 There is also an API(/checkExpType) that illustrates how one can use the experiment in an API.</p><p>🟡 The main logic is written in <strong>ExpIdentifierFilter.java</strong> class. This is a PreRequestFilter and is executed in every API request that comes in this application. Let’s go through the logic in this class.</p><h4><strong>ExpIdentifierFilter.java</strong></h4><pre>private long getExpIdentifier(HttpServletRequest httpServletRequest)</pre><p>This function returns the unique experiment identifier. In the first browser session, no “expId” cookie is received and so this function returns the current epoch timestamp. Then I set the “expId” cookie as that timestamp. In all further API calls in that browser session, this cookie will be received in the header and returned by this function.</p><pre>IExpIdentifierGetService expIdentifierGetService = expIdentifierGetFactory.getExpIdentifierService();</pre><p>This is a simple factory pattern based design by which I get to know which system is to be used: DB_BASED or PROPERTY_BASED. You would be using either of these systems, so you can Autowire the respective service directly instead of using a factory pattern based system.</p><p><strong>DB_BASED</strong>: All experiments and their configurations are stored in mysql server.</p><p><strong>PROPERTY_BASED</strong>: The system is based on a few simple properties. To change the configuration of an experiment, add/remove an experiment, etc. I’ll have to pass the new properties in command and restart the service.</p><pre>List&lt;ExpNameValueModel&gt; expNameValueModelList = expIdentifierGetService.getAllActiveExperiments();</pre><p>This will give us a list of all experiments. For DB_BASED, I run a simple query to get all experiments. For PROPERTY_BASED, I use the following 3 properties to get the list of all experiments.</p><pre>#This property has the names of experiments separated by &#39;;&#39;. Experiment cookies will be set by this name only.<br>traffic-split-service.exp-config.keys=exp1;exp2<br>#This property has the values of all respective experiments. The values of two different experiments are separated by &#39;;&#39; and values of one particular experiment are separated by &#39;,&#39;<br>traffic-split-service.exp-config.values=A,B,C,D;true,false<br>#This property has the traffic percentage of all respective experiments. The traffic split of two different experiments are separated by &#39;;&#39; and traffic percentages of one particular experiment are separated by &#39;,&#39;<br>traffic-split-service.exp-config.traffic-split=10,20,30,40;20,80</pre><p>Based on these properties, I collect the list of of all experiments.</p><p>For example, as per above properties, “exp1&quot; will have 4 variations. These variations and their respective traffic divisions are: A:10, B:20, C:30, D:40</p><pre>private String getExpValue(long expIdentifierValue, ExpNameValueModel expNameValueModel)</pre><p>I iterate over each experiment configuration and pass it in this function. I also pass the expIdentifierValue(expId) to this function. This function has the probability distribution logic and returns<strong> </strong>what value to be given to which experiment based on the value of expIdentifierValue.</p><p>Next I simply set the experiment key and value in request attribute, response header and cookie.</p><h4><strong>Code Optimizations:</strong></h4><p>One can add some code optimizations in the repository which I have written as comments(//todo:).</p><h4><strong>Why existing open source systems were not suitable for my need</strong>❓</h4><p>I found some open source feature flagging systems but none of them could fulfill all the requirements. This highlights the <strong>unique advantages</strong> of this system.</p><ol><li><strong>I need a flag that can be used by backend and frontend both</strong>: There were some systems which were compatible with certain tech stack only. Some other systems had multiple SDKs for different tech stacks but then I had to integrate the system separately in frontend and backend.</li><li><strong>I wanted the system to be very fast</strong>: I wanted the feature flag to be checked in every API call and the system should work when traffic is very high(scalable). This means that the system should be very fast so that no overhead is added to the API response time. Many open source systems use DBs to store flags for every user/browser session and then the experiment value is queried from the DB. This will make the system slow and also the cost will be high for storing so many sessions.</li><li>Many open source systems were free to some extent but after certain traffic limit, <strong>they charge money</strong>.</li><li><strong>Integrating the feature flag should be easy</strong>: Integration of feature flagging system should be easy so that it can be integrated in any project of any team easily. Many open source systems have too many features and are too complicated to integrate. Complicated integration means that implementing a minimalistic feature flag could take too much time in the release of a project. To integrate our system, one simply needs to add the PreRequestFilter class in java code and pass some properties.</li></ol><h4>🧐<strong>Drawbacks in the system:</strong></h4><p>Despite being adequate for my needs, the system does have its limitations, which users should be mindful of:</p><ol><li>The code is written in java backend only. But I think the same approach can be designed in any backend system and also it can be used by any frontend tech stack as flags are being set as a cookie in the browser.</li><li><strong>Sticky session and probability distribution can’t work hand-in-hand</strong>: Suppose the traffic split is 50–50% for an experiment. Now if one changes the traffic split to 80–20%, only new sessions will be split into 80–20% since old sessions will be sticky sessions. So one can’t expect the change in traffic split to be instant. It will take time for the sessions to be divided into 80–20% depending on traffic volume. This is an expected behaviour as sticky sessions and changes in probability distribution can’t be done simultaneously. There are some approaches to solve this problem but all of them are heavy in computation(time-taking).</li></ol><p><strong>Git repo:</strong> <a href="https://github.com/divyanshutw/Configurable-feature-flags">https://github.com/divyanshutw/Configurable-feature-flags</a></p><p>Feel free to clap👏 on this article and give stars🌟 to the repo.</p><p>The project is open source. Both the project and the blog are open for suggestions and comments.</p><p>Hope the article helps you. 💯💯</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd6058d3d34c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to add multiple language support in my android app — Dynamic Text‍]]></title>
            <link>https://divyanshutw.medium.com/how-to-add-multiple-language-support-in-my-android-app-dynamic-text-6fffe70631d4?source=rss-82ab8498ce6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fffe70631d4</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[ml-kit]]></category>
            <category><![CDATA[translation]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Divyanshutw]]></dc:creator>
            <pubDate>Sun, 31 Jan 2021 06:15:49 GMT</pubDate>
            <atom:updated>2021-01-31T06:15:49.803Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://divyanshutw.medium.com/how-to-add-multiple-language-support-in-my-android-app-static-text-9c131e40f606">How to add multiple language support in my android app — Dynamic Text👨‍💻</a></h3><p>In my previous article, I described how to enable multi-lingual support for your android application which uses just static text. You can find it <a href="https://divyanshutw.medium.com/how-to-add-multiple-language-support-in-my-android-app-static-text-9c131e40f606">here</a></p><p><a href="https://divyanshutw.medium.com/how-to-add-multiple-language-support-in-my-android-app-static-text-9c131e40f606">How to add multiple language support in my android app — Static Text👨‍💻</a></p><p>But most of the applications don’t just have static text. We have some text that comes from the backend as well. In this article, I’ll tell three different ways to translate the dynamic text. You can choose any one of them depending on your need. For me the third method worked well.</p><h4>🚀<strong>Using Google Cloud Translation Service:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*trWCB4JZwPwoYyZV" /><figcaption>Google Translation API</figcaption></figure><p>GCP offers Translation Service. Some of its advantages are:</p><p>🟢 Its easy to implement</p><p>🟢 You can buy plan according to your need. It has two services one for basic translations and other for advanced translations.</p><p>🟢 Since the models are remotely hosted in Google Cloud, the translation quality is also good.</p><p>Some of its disadvantages are:</p><p>🔴 💵It becomes costly if you implement it in many places inside your app.</p><p>🔴 Since the models are remotely hosted, it requires internet for translation to happen.</p><p>When is it best to use this: Its best to use in activities where you require high quality translation and such activities are less visited by the user.</p><p>You can read this article to know how to use the service: <a href="https://medium.com/@yeksancansu/how-to-use-google-translate-api-in-android-studio-projects-7f09cae320c7">https://medium.com/@yeksancansu/how-to-use-google-translate-api-in-android-studio-projects-7f09cae320c7</a></p><h4>🚀<strong>Implementing translation through your backend:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*3T14ZWh1ttPOatjl7s34BQ.png" /></figure><p>Another way to implement translation is through your backend. This means that the client sends the language code in which it wants the data. The server returns the text in the requested language. Some of the advantages of using this strategy are:</p><p>🟢 Its very easy to implement in both frontend and the backend. In frontend, you can store the language in the SharedPreferences and access it when needed.</p><p>🟢 Its cost effective in comparison to the previous method. This is because in google translation API, the billing is done on the basis of each translation. This means that if the user opens a certain activity 10 times, the translation will be done 10 times. But when the backend returns the translated text, the cost is required only to store the extra columns for different languages. Doesn’t matter how many times users open that activity, the cost will not grow and remain the same.</p><p>Some of the disadvantages of this strategy are:</p><p>🔴 💵The cost increases if you have large texts, too many rows or too many alternative languages.</p><h4>🚀<strong>Translating text using ML Kit translation API:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/0*IhCDkhKIir3xGnGB.png" /><figcaption>Src:<a href="https://developers.google.com/ml-kit/language/translation">https://developers.google.com/ml-kit/language/translation</a></figcaption></figure><p>This is a complete different approach from the above two. Because this time the translation is done on client’s device only.</p><p>The first time translation is done, the model is downloaded on the client’s device. After that the translation can be done without any internet. This seems to be best 👍. But it isn’t. Just like other methods, this also has some disadvantages:</p><p>🔴 The translation quality is not very good when it comes to translating bigger texts.</p><p><strong>🔴 </strong>The translation models are translated to and from English, i.e, if you want to translate from French to German, the text is first translated from French to English and then from English to German. This further reduces the translation quality for non-english languages.</p><p>🔴 You’ll have to adhere to some guidelines made by google like branding, etc. Read more about it <a href="https://cloud.google.com/translate/attribution">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ICMgkph8AFSokwpx.png" /><figcaption>Src:<a href="https://cloud.google.com/translate/attribution">https://cloud.google.com/translate/attribution</a></figcaption></figure><p>Now lets see how to use the API:</p><p>The API is very easy to implement. You can see the documentation <a href="https://developers.google.com/ml-kit/language/translation/android">here</a>.</p><p><strong><em>Step </em>1️⃣ : Language Identification</strong></p><p>This step is optional and depends on your need. In this step, we’ll identify the input language or the language coming from the server. Its good if we know our source language, otherwise we can apply this step to know it.</p><p>Add dependency in build.gradle (app level)</p><pre>implementation &#39;com.google.mlkit:language-id:16.1.1&#39;</pre><p>Now add following code in your activity/fragment:</p><pre>val languageIdentifier=LanguageIdentification.getClient()<br>binding.button.setOnClickListener <strong>{<br>    </strong>languageIdentifier.identifyLanguage(binding.editText.<em>text</em>.toString())<br>        .addOnCompleteListener <strong>{<br>            </strong>if(<strong>it</strong>.<em>isSuccessful</em>)<br>            {<br>                if(<strong>it</strong>.<em>result</em>!=null)<br>                {<br>                    if(<strong>it</strong>.<em>result</em>!=&quot;und&quot; &amp;&amp; TranslateLanguage.fromLanguageTag(<strong>it</strong>.<em>result</em>!!)!=null)<br>                    {<br>                        Log.d(&quot;div&quot;,&quot;Translate L35 ${<strong>it</strong>.<em>result</em>} ${TranslateLanguage.fromLanguageTag(<strong>it</strong>.<em>result</em>!!)}&quot;)<br>                        binding.textViewCurrentLanguage.<em>text</em>=<strong>it</strong>.<em>result<br>                        </em>translate(binding.editText.<em>text</em>.toString(), TranslateLanguage.fromLanguageTag(<strong>it</strong>.<em>result</em>!!)!!)<br>                    }<br>                    else<br>                        binding.textViewCurrentLanguage.<em>text</em>=&quot;Undefined Language&quot;<br>                }<br>                else<br>                    binding.textViewCurrentLanguage.<em>text</em>=&quot;null&quot;<br>            }<br>            else<br>            {<br>                binding.textViewCurrentLanguage.<em>text</em>=&quot;Error ${<strong>it</strong>.<em>exception</em>}&quot;<br>                Log.d(&quot;div&quot;,&quot;Identification Task Failed ${<strong>it</strong>.<em>exception</em>}&quot;)<br>            }<br>        <strong>}<br>}</strong></pre><p>The language identifier API returns “und” for undefined language otherwise it returns the language code.</p><p><strong><em>Step </em>2️⃣ : Translate the text</strong></p><p>Now we’ll call the translate function as follows:</p><pre>private fun translate(text: String, fromLang: String) {<br>    val options=TranslatorOptions.Builder()<br>        .setSourceLanguage(fromLang)<br>        .setTargetLanguage(toLang)<br>        .build()<br>    val translator=Translation.getClient(options)<br><br>    val conditions=DownloadConditions.Builder()<br>        .build()                                        //You can provide conditions like wifi and charging here<br>    translator.downloadModelIfNeeded(conditions)<br>        .addOnCompleteListener <strong>{ </strong>it1 <strong>-&gt;<br>            </strong>if(it1.<em>isSuccessful</em>)<br>            {<br>                Toast.makeText(requireContext(),&quot;Translation model downloaded successfully&quot;,Toast.<em>LENGTH_LONG</em>).show()<br>                translator.translate(text)<br>                    .addOnCompleteListener <strong>{<br>                        </strong>if(<strong>it</strong>.<em>isSuccessful</em>)<br>                        {<br>                            binding.textView.<em>text</em>=<strong>it</strong>.<em>result<br>                            </em>Log.d(&quot;div&quot;,&quot;Translation successful ${<strong>it</strong>.<em>result</em>}&quot;)<br>                        }<br>                        else<br>                        {<br>                            Toast.makeText(requireContext(),&quot;Translation failed&quot;,Toast.<em>LENGTH_LONG</em>).show()<br>                            Log.d(&quot;div&quot;,&quot;Translation Task failed ${<strong>it</strong>.<em>exception</em>}&quot;)<br>                        }<br>                    <strong>}<br>            </strong>}<br>            else<br>            {<br>                Toast.makeText(requireContext(),&quot;Translation model couldn&#39;t be downloaded&quot;,Toast.<em>LENGTH_LONG</em>).show()<br>                Log.d(&quot;div&quot;,&quot;Translation Download Task failed ${it1.<em>exception</em>}&quot;)<br>            }<br>        <strong>}<br></strong>}</pre><p>Here in the code, we firstly made a client for translation.</p><p>Then we downloaded the model if needed. The Translation API does it itself using the DownloadManager. Once the model is downloaded, the translation can be done without any internet.</p><p><strong>Just that and congratulations you have successfully added multi language support to your app with dynamic text. </strong>🥳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/0*UT6lsqHcSB5qEKMN.gif" /></figure><p>For full code, see this <a href="https://github.com/divyanshutw/MLKit_NLP">repository</a> — <a href="https://github.com/divyanshutw/MLKit_NLP">https://github.com/divyanshutw/MLKit_NLP</a></p><p><a href="https://github.com/divyanshutw"><strong>Github</strong></a><strong> — </strong><a href="https://github.com/divyanshutw"><strong>https://github.com/divyanshutw</strong></a></p><p><a href="https://www.linkedin.com/in/divyanshu-tiwari-7a7318173"><strong>LinkedIn</strong></a><strong> — </strong><a href="https://www.linkedin.com/in/divyanshu-tiwari-7a7318173"><strong>https://www.linkedin.com/in/divyanshu-tiwari-7a7318173</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fffe70631d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to add multiple language support in my android app — Static Text‍]]></title>
            <link>https://divyanshutw.medium.com/how-to-add-multiple-language-support-in-my-android-app-static-text-9c131e40f606?source=rss-82ab8498ce6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c131e40f606</guid>
            <category><![CDATA[translation]]></category>
            <category><![CDATA[multilingual]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[language]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Divyanshutw]]></dc:creator>
            <pubDate>Wed, 27 Jan 2021 11:27:10 GMT</pubDate>
            <atom:updated>2021-01-27T11:27:10.087Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to add multiple language support in my android app — Static Text👨‍💻</h3><p>We live in a world with diverse languages. India only has 22 primary languages. That’s why we see that most of the global apps and the local Indian apps have multi language support. There are two types of texts that we show in our app depending on their origin:</p><p>📱<strong>Static :</strong> It includes all the text that is static, i.e., the text is written inside the app as a string. This includes all the text in the xml files, class files, etc.</p><p>🌐<strong>Dynamic :</strong> It includes all the text that is dynamically fetched from a remote database through firebase, some API, etc.</p><p>Both of the strings are dealt in a different manner. In this part, we’ll talk about just the static text. There are different ways to do this. The one you’ll need depends on you requirements but I’ll cover them all.</p><blockquote><strong>⚠️THIS ARTICLE IS BEGINNER FRIENDLY</strong></blockquote><blockquote><strong>CASE 1 :-</strong> If you want your app to change language depending on the user’s default language, then this case is for you. This task is pretty simple and includes following steps:</blockquote><ol><li>Place all the texts in the strings.xml file.</li><li>Add locale(s) in the translation editor.</li><li>Convert strings.xml into an excel file.</li><li>Translate all the text fields using google translate.</li><li>Convert the excel file back into strings.xml file.</li></ol><p>Now lets see each of these in detail :</p><p><strong><em>Step </em>1️⃣ : Place all the texts in the strings.xml file : </strong>One should always keep all the texts in the strings.xml file. You can find it here in your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*MSLeTBmKeFjYq_VgeUtthg.png" /></figure><p>Android studio offers a simple way to do it. Just click alt+enter(windows/linux) or option+enter(mac) on a string whether inside a xml file or any other file. You’ll get an option saying “Extract string resource”. This will extract string resource for that string. After making a resource, you can access the string using “@string/string_resource_id” in xml file and using “getString(R.string.string_resource_id)” in kotlin class files with context.</p><p>Doing this is always a good practice and is an important aspect for making scalable apps.</p><p><strong><em>Step </em>2️⃣ : Add locale(s) in the translation editor :</strong> Go to strings.xml and there you’ll find a notification at the top at the right end of which you’ll find an option saying “Open editor”. Click on it. You may also open Translation editor by right clicking on strings.xml from the android panel and selecting the “Open Translation Editor” in the bottom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*03ACbgyNACbS39VKXVHLmg.png" /></figure><p>Now click on the button as shown and choose the locale or the language you want to make available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*Y-lw4lM9HSls8bugWwtrKA.png" /></figure><p><strong><em>Step </em>3️⃣ : Convert strings.xml into an excel file :</strong> You can do this using this <a href="https://www.convertcsv.com/xml-to-csv.htm">website</a>. There might be some discrepancies if you have large number of keys, so its recommended to have a look on the excel file once.</p><p><strong><em>Step </em>4️⃣ : Translate all the text fields using google translate :</strong> Now make a copy of this excel file and delete the column containing the text in English. Copy all the texts from the original excel file in English and translate it into desired language using <a href="https://translate.google.co.in/">this</a>. Copy the converted texts and paste into the empty column in the new excel file.</p><p><strong><em>Note : </em></strong><em>For untranslatable strings, you may copy the same text as in original excel file and paste it back in the new one as it is without translating. You may also do this in the Translation Editor by checking the Untranslatable check box.</em></p><p><strong><em>Step </em>5️⃣ :</strong>Convert the new excel file back into the xml file using <a href="https://www.convertcsv.com/xml-to-csv.htm">this</a>. Take care of using the proper xml tags.</p><p>When you added a locale, another strings.xml file was created by android studio in the same folder in which the original strings.xml was there as shown here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*MSLeTBmKeFjYq_VgeUtthg.png" /></figure><p>Go to this new strings.xml file and paste the content of your strings.xml that you created from the excel file after translation.</p><p><strong>Just that……And when you change the language from your phone’s settings, the app language will also change.</strong>🥳</p><blockquote><strong>CASE 2 :-</strong> You might have seen that when you install an app, it asks you to set a language for your app. If you want to implement this, then this case is for you.</blockquote><p>Firstly, you’ll have to do everything as in CASE 1 and then follow these steps :</p><ol><li>Add a screen to ask the user to set language.</li><li>Store the current language in the SharedPreferences.</li><li>Change the locale of your app.</li><li>Add the ChangeLanguage class to your app.</li><li>Restart the activity to see the changes.</li></ol><p>Now lets see each of these in detail :</p><p><strong><em>Step </em>1️⃣ : Add a screen to ask the user to set language :</strong> This is totally on your choice on how you do it. You can use a ListView, RadioGroup or anything else you like. I have used RadioGroup here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*JQTeSovAgbXNxuZozAp7dw.png" /></figure><p><strong><em>Step </em>2️⃣ : Store the current language in the SharedPreferences :</strong> Make a SharedPreferences and store the current language inside it.</p><pre>var preferences: SharedPreferences? = null<br>var editor: SharedPreferences.Editor? = null<br>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>    setContentView(R.layout.<em>activity_main</em>)<br>    <br>    preferences = getSharedPreferences(&quot;LANGUAGE&quot;, Context.<em>MODE_PRIVATE</em>)<br>    editor= preferences!!.edit()<br><br>    val currentLanguage=preferences!!.getString(&quot;language&quot;, &quot;English&quot;)<br>    if(currentLanguage==&quot;English&quot;)<br>        findViewById&lt;RadioButton&gt;(R.id.<em>radioButton_english</em>).<em>isChecked</em>=true<br>    else<br>        findViewById&lt;RadioButton&gt;(R.id.<em>radioButton_hindi</em>).<em>isChecked</em>=true<br><br>    findViewById&lt;Button&gt;(R.id.<em>button_ok</em>).setOnClickListener <strong>{<br>        </strong>val selectedId=findViewById&lt;RadioGroup&gt;(R.id.<em>radioGroup</em>).<em>checkedRadioButtonId<br>        </em>when(selectedId){<br>            R.id.<em>radioButton_english </em>-&gt; {<br>                setLanguage(&quot;English&quot;, &quot;en&quot;)<br>            }<br>            R.id.<em>radioButton_hindi </em>-&gt; {<br>                setLanguage(&quot;Hindi&quot;, &quot;hi&quot;)<br>            }<br>        }<br>    <strong>}<br><br>    </strong>findViewById&lt;Button&gt;(R.id.<em>button_test</em>).setOnClickListener <strong>{<br>        </strong>startActivity(Intent(this,TextActivity::class.<em>java</em>))<br>    <strong>}<br></strong>}</pre><p><strong><em>Step </em>3️⃣ : Change the locale of your app : </strong>You can change locale programmatically as follows :</p><pre>private fun setLanguage(language: String, languageCode: String) {<br>    editor?.putString(&quot;language&quot;, language)<br>    editor?.commit()<br>    val locale = Locale(languageCode)<br>    Locale.setDefault(locale)<br>    val config = Configuration()<br>    config.locale = locale<br>    <em>resources</em>.updateConfiguration(config, <em>resources</em>.<em>displayMetrics</em>)<br><br>    val intent = Intent(this, MainActivity::class.<em>java</em>)<br>    intent.<em>flags </em>= Intent.<em>FLAG_ACTIVITY_CLEAR_TOP<br>    </em>startActivity(intent)<br>    Toast.makeText(this, &quot;Language changed&quot;, Toast.<em>LENGTH_LONG</em>).show()<br>    finish()<br>}</pre><p><strong><em>Step </em>4️⃣ : Add the ChangeLanguage class to your app : </strong>This will update the locale of your app. But the problem is that the app won’t remember what locale was set once you move to a different page or close the activity.</p><p>To solve this problem, make a new class ChangeLanguage.kt and add the following code in it :</p><pre>import android.content.Context<br>import android.content.SharedPreferences<br>import android.content.res.Configuration<br>import java.util.*<br><br>class ChangeLanguage(private val context: Context) {<br>    var preferences: SharedPreferences? = null<br>    var editor: SharedPreferences.Editor? = null<br>    fun setLanguage() {<br>        preferences = context.getSharedPreferences(&quot;LANGUAGE&quot;, Context.<em>MODE_PRIVATE</em>)<br>        editor= preferences!!.edit()<br><br>        var language=&quot;English&quot;<br>        var languageCode=&quot;en&quot;<br>        var currentLanguage=&quot;English&quot;<br>        if(preferences!!.contains(&quot;language&quot;))<br>        {<br>            currentLanguage=preferences!!.getString(&quot;language&quot;, &quot;English&quot;)!!<br>            if(currentLanguage==&quot;English&quot;)<br>            {}<br>            else<br>            {language=&quot;Hindi&quot;;languageCode=&quot;hi&quot;}<br>        }<br><br>        editor?.putString(&quot;language&quot;, language)<br>        editor?.commit()<br><br>        val locale = Locale(languageCode)<br>        Locale.setDefault(locale)<br>        val config = Configuration()<br>        config.locale = locale<br>        context.<em>resources</em>.updateConfiguration(config, context.<em>resources</em>.<em>displayMetrics</em>)<br>    }<br><br>    fun getLanguage():String<br>    {<br>        val preferences: SharedPreferences=context.getSharedPreferences(&quot;LANGUAGE&quot;, Context.<em>MODE_PRIVATE</em>)<br>        var language=&quot;english&quot;<br>        if(preferences.contains(&quot;language&quot;))<br>            language=preferences.getString(&quot;language&quot;,&quot;English&quot;)!!.<em>toLowerCase</em>()<br>        return language<br>    }<br>}</pre><p>Now you’ll have to call this class before inflating any activity or fragment.</p><pre>ChangeLanguage(this).setLanguage()<br>setContentView(R.layout.<em>activity_text</em>)</pre><p><em>Note that you’ll have to call the class before setting the layout in case of activity.</em></p><p><strong><em>Step </em>5️⃣ :</strong> After doing all this you won’t see the changes in your current activity if you don’t restart it.</p><p><strong>Just that and congratulations you have successfully added multi language support to your app with static text. </strong>🥳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/0*s5QUeZYPYb-2y5x-.gif" /></figure><p>For full code, see this <a href="https://github.com/divyanshutw/Multi-Language-Static">repository</a> — <a href="https://github.com/divyanshutw/Multi-Language-Static">https://github.com/divyanshutw/Multi-Language-Static</a></p><p><a href="https://github.com/divyanshutw"><strong>Github</strong></a><strong> — </strong><a href="https://github.com/divyanshutw"><strong>https://github.com/divyanshutw</strong></a></p><p><a href="https://www.linkedin.com/in/divyanshu-tiwari-7a7318173"><strong>LinkedIn</strong></a><strong> — </strong><a href="https://www.linkedin.com/in/divyanshu-tiwari-7a7318173"><strong>https://www.linkedin.com/in/divyanshu-tiwari-7a7318173</strong></a></p><p>I’ll explain how to deal with dynamic text in my next article. So stay tuned. 🙃🙃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c131e40f606" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make an offline cache in android using Room database and MVVM architecture? ‍]]></title>
            <link>https://divyanshutw.medium.com/how-to-make-an-offline-cache-in-android-using-room-database-and-mvvm-architecture-6d1b011e819c?source=rss-82ab8498ce6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d1b011e819c</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[room-database]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Divyanshutw]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 04:15:49 GMT</pubDate>
            <atom:updated>2021-01-20T04:15:49.615Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How to make an offline cache in android using Room database and MVVM architecture? </strong>👨‍💻</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*16p6QkfkIs9XmnK7" /></figure><p><strong>Introduction:</strong></p><p>No one likes the buffering animation. Android apps should have an offline cache for data that is fetched from the internet and is needed frequently. After all it also saves the internet bill of the user and the app can be used offline also with outdated data. Here in this article I’ll tell you how you can easily implement offline caching in your android app using the Room database.💯</p><h3>⚠️This article contains concepts</h3><p>If you’re using MVVM in your application, it will suit you best but you’ll at least get to know the concept even if you’re using some other architecture.</p><p>Let me first tell you briefly how we’ll do this. But before that I think I should put on a disclaimer that there is <em>a lot of boilerplate code involved in this</em>🥵. So don’t worry seeing all the classes🤗. We’ll:</p><ol><li>import the dependencies of the room database</li><li>make a data class to hold the data object</li><li>make the DAO with suitable SQL queries</li><li>make the database class</li><li>make the repository class</li><li>write some code in the ViewModel class</li><li>Make the ViewModeFactory class</li></ol><p><strong>But before starting, the question is why to use Room database only</strong>🤔</p><p>You may argue that I’ll rather use a local file system for my offline caching needs. Of Course you may do that but the file system is meant to store files like image, video, text, etc. and not the sequential data or tabular data. Another argument can be the use of shared preferences. They can be used to store data in form of key and value pairs but it also has a limitation that only a limited data can be stored in it.</p><p>So a room database is the best option. Some of the reasons why you should use it are ➛ it’s easy to set up,➛ using LiveData we can easily make our app with real time updates,➛ we can write queries in SQL and a lot more.</p><p><strong>Architecture:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/0*ailEWH4RAkdgOtbf" /></figure><p>We have two sources of data at any given time. One is the room database stored inside the device and the other is the data fetched from the server. So the question is which to use to show in the UI❓ We create another class called the repository. All the data is fetched from the repository only. All the chaos of updating the local room database, etc. goes inside this repository only.</p><p>In the UI we show the data from the repository which shows the LiveData from the Room database. Simultaneously, we fetch the data from the API, i.e., from the server and update the Room database. Now the LiveData is changed and the observer gets called. This updates the UI.</p><blockquote><strong>Remember:</strong> Room database is the single source of truth</blockquote><p><strong>Concept of Get request:</strong></p><p>🟠For the first time the repository is empty as the room database is empty and the API also hasn’t returned anything yet. So, till then we can show the loading dialog or something to let the user know that the data is being fetched.</p><p>🟠Now when the API returns the response successfully, we save the response in the Room database using the Insert query.</p><p>🟠The repository returns the LiveData object from the Room database which was empty till now. But now it has data in it. So the observer of the LiveData gets called.</p><p>🟠Finally, the UI is updated and the loading dialog is dismissed.</p><p>🟠This is what happens for the first time. For the rest of the times, we do exactly the same thing except that the loading dialog is not shown.</p><p><strong>Concept of Put, Post or Delete request</strong></p><p>When we update the data, say we want to insert row(s) or delete row(s), we update our server first using the API and then the Room database is updated. The reason we update the server first is hidden in the following question: Which is likely to fail more, Update request to the server or update request to the Room database❓ The answer is obvious: The update request to the server is more likely to fail because of a number of reasons like no internet connection, slow internet, high network traffic, etc.</p><p>So if we update the Room database first there is a high chance of discrepancy being created between the local and the remote database.</p><blockquote>Lets see the steps now.</blockquote><p>🟡We send the update request to the server and start showing the uploading dialog or something to let the user know that the data is being uploaded.</p><p>🟡Once the data is uploaded, stop showing the dialog.</p><p>🟡Now we also have to update the UI. Refresh the repository by following the same steps as in the get request.</p><p>🟡Again the LiveData gets changed, observer gets called and the UI is updated.</p><p>🟡Or you can also follow another approach which will save time and the internet but you’ll have to write a bit more code. You can update the Room database yourself once the server is updated.</p><p><strong>Now let’s implement what we discussed</strong></p><blockquote>Step 1️⃣: Import the dependencies of Room database</blockquote><p>You may refer <a href="https://developer.android.com/training/data-storage/room">this</a> page to import all the dependencies.</p><p>You’ll also have to implement the coroutines. I am using data binding also which is optional.</p><blockquote>Step 2️⃣: Make a data class to hold the data object</blockquote><p>This is where you make all the columns for your SQL table. Here the table name is “cars_table”. You can use the annotations as given. There should be a primary key for which I have set autoGenerate=true. Rest all is simple. The names of the columns written inside parenthesis within inverted commas are the ones used by the table and the normal variable names are for our general purpose use.</p><pre>package com.practice.offlinecaching<br><br>import androidx.room.ColumnInfo<br>import androidx.room.Entity<br>import androidx.room.PrimaryKey<br><br>@Entity(tableName=&quot;cars_table&quot;)<br>data class Cars(<br>    @PrimaryKey(autoGenerate = true)<br>    var cardId:Long=0,<br><br>    @ColumnInfo(name=&quot;image_url&quot;)<br>    var imageURL:String?=null,<br><br>    @ColumnInfo(name=&quot;name&quot;)<br>    var name:String?=null,<br><br>    @ColumnInfo(name=&quot;category&quot;)<br>    var category:String?=null<br>)</pre><blockquote>Step 3️⃣: Make the DAO with suitable SQL queries</blockquote><p>Data Access Object is the interface where we write our SQL queries. Different annotations are used here. Read <a href="https://developer.android.com/reference/android/arch/persistence/room/Dao">this</a> for further assistance.</p><p>Note that we are returning the LiveData of the list of Cars object.</p><p>Another important thing to note is the Insert query. We’re using onConflict = OnConflictStrategy.REPLACE</p><p>What this does is that in case of any conflict between the current row and the row that is being inserted, we replace the new row over the previous one. Read more about it <a href="https://developer.android.com/reference/android/arch/persistence/room/OnConflictStrategy">here</a>.</p><pre>package com.practice.offlinecaching<br><br>import android.content.Context<br>import androidx.lifecycle.LiveData<br>import androidx.room.*<br><br>@Dao<br>interface CarsDao<br>{<br>    @Query(&quot;select * from cars_table where category= :key&quot;)<br>    fun getCarsFromRoom(key:String): LiveData&lt;List&lt;Cars&gt;&gt;<br><br>    @Insert(onConflict = OnConflictStrategy.<em>REPLACE</em>)<br>    fun insertCarsToRoom(cars:List&lt;Cars&gt;)<br>}</pre><blockquote>Step 4️⃣: Make the database abstract class and the getDatabase function.</blockquote><p>This is just a boilerplate code. The abstract class database is made with the entity of Database. This class simply represents the database and it inherits the RoomDatabase(). We’ll talk about this class some other time but now lets make another function that returns an instance of the database, getDatabase()</p><pre>@Database(entities = [Cars::class],version=1,exportSchema = false)<br>abstract class CarsDatabase : RoomDatabase() {<br>    abstract val CarsDatabaseDao: CarsDao<br>}<br><br>private lateinit var <em>INSTANCE</em>:CarsDatabase<br><br>fun getDatabase(context: Context):CarsDatabase<br>{<br>    if(!::<em>INSTANCE</em>.<em>isInitialized</em>)<br>    {<br>        <em>INSTANCE</em>=<br>            Room.databaseBuilder(context.<em>applicationContext</em>,CarsDatabase::class.<em>java</em>,&quot;cars_database&quot;)<br>                .fallbackToDestructiveMigration().build()<br><br>    }<br>    return <em>INSTANCE<br></em>}</pre><blockquote>Step 5️⃣: Make the repository class</blockquote><p>Repository is where we fetch data from the server and update our local Room database. In my case I am fetching the data in the refreshCars(String,String) method. Two parameters are just to tell you how we can send the parameters here. It is a suspend function because it is called from the viewModelScope. This is where the use of kotlin coroutines comes into play. It avoids the blocking of the UI thread while the data is being fetched from the server. ⌚️</p><p>Note that the class has a database variable in its constructor. It is used to insert the data fetched from the server to the Room database.</p><p>We also have a function to get the data from the Room database called the getCars(String) method. It also uses the database variable and returns a LiveData object that it gets back from the Room database.</p><pre>package com.practice.offlinecaching<br><br>import android.os.AsyncTask<br>import android.util.Log<br>import androidx.lifecycle.LiveData<br>import com.androidnetworking.AndroidNetworking<br>import com.androidnetworking.common.Priority<br>import com.androidnetworking.error.ANError<br>import com.androidnetworking.interfaces.JSONObjectRequestListener<br>import kotlinx.coroutines.Dispatchers<br>import kotlinx.coroutines.withContext<br>import org.json.JSONArray<br>import org.json.JSONObject<br><br><br>class CarsRepository(private val database: CarsDatabase)<br>{<br><br>    fun getCars(key:String?): LiveData&lt;List&lt;Cars&gt;&gt; {<br>        return database.CarsDatabaseDao.getCarsFromRoom(key!!)<br>    }<br><br>    suspend fun refreshCars(type: String?,token:String?)<br>    {<br>        withContext(Dispatchers.IO)<strong>{<br>            </strong>var url=&quot;&quot;<br>            AndroidNetworking.get(url)<br>                .setPriority(Priority.<em>HIGH</em>)<br>                .build()<br>                .getAsJSONObject(object : JSONObjectRequestListener {<br>                    override fun onResponse(response: JSONObject?) {<br>                        if (response != null) {<br><br><br>                            var carsListData = response.get(&quot;data&quot;) as JSONArray<br>                            val list = ArrayList&lt;Cars&gt;()<br>                            var i = 0<br>                            while (i &lt; carsListData.length()) {<br>                                //Insert the data into the list<br>                            }<br>                            AsyncTask.execute <strong>{   </strong>database.CarsDatabaseDao.insertCarsToRoom(list)<br>                            <strong>}<br>                        </strong>}<br>                    }<br>                    override fun onError(anError: ANError?) {}<br>                })<br>        <strong>}<br>    </strong>}<br>}</pre><blockquote>Step 6️⃣: ViewModel class</blockquote><p>An instance of the repository class is created and in the init block we fetch the LiveData object from the repository. The rest of the code depends upon your use case.</p><pre>package com.practice.offlinecaching<br><br>import android.app.Application<br>import androidx.lifecycle.AndroidViewModel<br>import androidx.lifecycle.MutableLiveData<br>import kotlinx.coroutines.CoroutineScope<br>import kotlinx.coroutines.Dispatchers<br>import kotlinx.coroutines.Job<br>import kotlinx.coroutines.launch<br><br>class CarsViewModel(application: Application, val type: String?, val token:String?) : AndroidViewModel(<br>    application)<br>{<br>    private val viewModelJob= <em>Job</em>()<br>    private val viewModelScope= <em>CoroutineScope</em>(viewModelJob + Dispatchers.Main)<br><br>    private val database= <em>getDatabase</em>(application)<br>    private val carsRepository=CarsRepository(database)<br><br>    init {<br>        viewModelScope.<em>launch </em><strong>{<br>            </strong>carsRepository.refreshCars(type,token)<br>        <strong>}<br>    </strong>}<br><br>    val carsTypeList=carsRepository.getCars(type)<br><br>    override fun onCleared() {<br>        super.onCleared()<br>        viewModelJob.cancel()<br>    }<br>}</pre><blockquote>Step 7️⃣: Make the ViewModelFactory class</blockquote><p>It has a simple boilerplate code. You must already know about this if you’re using the MVVM architecture. It returns the instance of ViewModel class.</p><pre>package com.practice.offlinecaching<br><br>import android.app.Application<br>import androidx.lifecycle.ViewModel<br>import androidx.lifecycle.ViewModelProvider<br><br>class CarsViewModelFactory(val app:Application, val type:String?, val token:String?) : ViewModelProvider.Factory {<br><br><br>    override fun &lt;T : ViewModel?&gt; create(modelClass: Class&lt;T&gt;): T {<br>        if (modelClass.isAssignableFrom(CarsViewModel::class.<em>java</em>)) {<br>            @Suppress(&quot;UNCHECKED_CAST&quot;)<br>            return CarsViewModel(app,type,token) as T<br>        }<br>        throw IllegalArgumentException(&quot;Unable to construct viewmodel&quot;)<br>    }<br>}</pre><p><strong>Just that and congratulations you have successfully implemented the offline caching. </strong>🥳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/0*D726CGc61PRAGowq.gif" /></figure><p>For full code, see this <a href="https://github.com/divyanshutw/Offline-caching">repository</a>: <a href="https://github.com/divyanshutw/Offline-caching">https://github.com/divyanshutw/Offline-caching</a></p><p><a href="https://github.com/divyanshutw"><strong>Github</strong></a><strong> — </strong><a href="https://github.com/divyanshutw"><strong>https://github.com/divyanshutw</strong></a></p><p><a href="https://www.linkedin.com/in/divyanshu-tiwari-7a7318173"><strong>LinkedIn</strong></a><strong> — https://www.linkedin.com/in/divyanshu-tiwari-7a7318173</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d1b011e819c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>