<?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 Hamid Gharehdaghi on Medium]]></title>
        <description><![CDATA[Stories by Hamid Gharehdaghi on Medium]]></description>
        <link>https://medium.com/@hamidgh?source=rss-156639da0783------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RvHIlfIyrxCJffbeMjQpSg.png</url>
            <title>Stories by Hamid Gharehdaghi on Medium</title>
            <link>https://medium.com/@hamidgh?source=rss-156639da0783------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:24:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hamidgh/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[Dynamically change bundled strings]]></title>
            <link>https://medium.com/@hamidgh/dynamically-change-bundled-strings-a24b97bfd306?source=rss-156639da0783------2</link>
            <guid isPermaLink="false">https://medium.com/p/a24b97bfd306</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Hamid Gharehdaghi]]></dc:creator>
            <pubDate>Thu, 22 Mar 2018 09:05:39 GMT</pubDate>
            <atom:updated>2020-05-28T18:56:46.824Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to Restring your app</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueq0n_xcmcvOc3l-IwtUdw.jpeg" /><figcaption>Image by <a href="http://www.topguitar.xyz/2017/10/how-to-restring-electric-guitar-with.html">TopGuitar</a></figcaption></figure><p>Providing string resources as XML files is how we manage static texts of an application in Android. There’s a problem with this approach: every time we want to change a text we have to release a new version or wait for the next release time. That’s why in some projects we decide to implement a system which allows us to change this static bundled text dynamically and from server-side. But this is not that easy(or let’s say clean) in Android. Let’s see how we can do it.</p><p>Here I will explain a simple implementation very briefly in first section which as I said is not easy and clean. Then I will introduce my alternative way in second section. if you’re too lazy to read the article completely, just jump to the second section.</p><h3>1. A simple implementation</h3><p>For a simple implementation, we should at least do these steps:</p><ol><li>Implement a repository of new strings: here we should load strings from server-side( and cache them probably) and provide a nice interface to other components to search for new strings.</li><li>We have to change the all cases where we use bundled string resources to display a text in Java/Kotlin code:</li></ol><p>So instead of these lines:</p><pre>1) String msg = Context.getString(R.string.message);<br>2) MyTextView.setText(R.string.title);</pre><p>We should write something like this:</p><pre>1) String msg = StringsRepository.getString(R.string.message);<br>2) MyTextView.setText(StringsRepository.getString(R.string.title));</pre><p>So we should have(or inject) StringsRepository in kinda everywhere.</p><p>3. We have to change the strings used in XML layout files. This part is kinda tricky, because we can just use static resources in our XML files. So we have two options:</p><ul><li>Instead of setting strings in XML files, set them in Java/Kotlin code one-by-one. So probably after inflating each layout we will have bunch of view.setText() lines.</li></ul><pre>View view = LayoutInflater.from(context).inflate(R.layout.mylayout, parent, null);<br>((TextView)view.findViewById(R.id.text1)).setText(...);<br>((TextView)view.findViewById(R.id.text2)).setText(...);<br>...</pre><ul><li>As an alternative, we can write a method which gets a root layout as an input and traverse the tree of views and tries to change their text. This method can be like a helper class which can be used everywhere, but still will need to have access to StringsRepository instance.</li></ul><p>4. We can also create some custom views which extend the standard views and can handle getting the strings from repository internally. So as an example, instead of TextView we will have CustomTextView which when we call .setText(int strResId) it will try to get this string from StringsRepository instead of Context. CustomTextView needs to have access to StringsRepository and we need to use this new component everywhere instead of TextView.</p><pre>public class CustomTextView extends AppCompatTextView {<br>  private StringsRepository stringsRepository;</pre><pre>  @Override<br>  public void setText(int strResId) {<br>    setText(stringsRepository.getString(strResId));<br>  }<br>}</pre><p>I didn’t want to go to more details, but as you can see even this simple implementation is not that clean as we expect, and we need to apply a lot of changes. Here I also just assumed that we have only TextViews for simplicity, but in a real application it’s not the case. We will have more view to change(EditText, Toolbar, …) and each has more attributes(hint, title, …).</p><h3>2. Use <a href="https://github.com/hamidness/restring">Restring</a> library</h3><p>As an alternative to the messy implementation we mentioned, we can use Restring library which makes overriding the static string resources really easy. Here is the steps to implement it:</p><p><strong>1. Add dependency:</strong></p><pre>implementation &#39;com.ice.restring:restring:1.0.0&#39;</pre><p><strong>2.</strong> <strong>Initialize:<br></strong>We can do this in Application class.</p><pre>Restring.init(context);</pre><p><strong>3.</strong> <strong>Inject into context:</strong><br>if there’s a BaseActivity it can be added there, otherwise it should be added to all of the activities!</p><pre>@Override<br>protected void attachBaseContext(Context newBase) {<br>    super.attachBaseContext(Restring.wrapContext(newBase));<br>}</pre><p><strong>4. Load and set the new strings:</strong></p><p>Whenever/however/wherever the new strings are loaded, we can set them into Restring like this:</p><pre>Restring.setStrings(language, newStrings);</pre><p><strong>5. Done!</strong></p><p>That’s it! now all the static strings will be overridden by new strings. For more configurations you can check <a href="https://github.com/hamidness/restring">Restring Github page</a>.</p><h3>3. Adding a new language support to your app</h3><p>With Restring, for adding a new language to your application, we don’t have to release a new app version. Just send the string translations from server-side for the new language to app, and app will set them as strings of the new language and that’s it.</p><p>Let’s say we gonna add German language. Let’s assume we have an API which returns the list of string translations for all supported languages. So in server-side we add the new language. So we will have:</p><pre>[<br>  &quot;en&quot;: [<br>    &quot;home_title&quot;: &quot;Welcome!&quot;,<br>    &quot;button_cancel&quot;: &quot;Cancel&quot;,<br>    ...<br>  ],</pre><pre>  &quot;de&quot;: [<br>    &quot;home_title&quot;: &quot;Willkommen!&quot;,<br>    &quot;button_cancel&quot;: &quot;Stornieren&quot;,<br>    ...<br>  ]<br>]</pre><p>Now that we have strings for German language in API response we can simply do this:</p><pre>Map&lt;String, Map&lt;String, String&gt;&gt; langStrings = ... //parse the json<br>for(Map.Entry&lt;String, Map&lt;String, String&gt;&gt; lang: langStrings) {<br>  Restring.setStrings(lang.getKey(), lang.getValue());<br>}</pre><p>Now if we change our Android device language, Restring will start using the new language strings.</p><p><strong>Note:</strong> Restring uses current locale strings. So if we call Locale.setDefault(…) to set a new locale, Restring will also uses the new locale to display the texts.</p><h3>Conclusion</h3><p>Changing the static bundled texts from server-side is a painful task. Restring is created to make this easier. I hope it can help and get better!</p><p>You can check <a href="https://github.com/hamidness/restring">Restring Github page</a> for more details about configuration.</p><p><strong>UPDATE: </strong>I didn’t have enough time to maintain the library, so Benedikt Löbbecke forked, and continued developing and maintaining that. You should use that version if you gonna use the library. here you can find his version on <a href="https://github.com/B3nedikt/restring">https://github.com/B3nedikt/restring</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a24b97bfd306" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dagger multibinding — Sets and Maps]]></title>
            <link>https://medium.com/@hamidgh/dagger-multibinding-sets-and-maps-713254b7f734?source=rss-156639da0783------2</link>
            <guid isPermaLink="false">https://medium.com/p/713254b7f734</guid>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Hamid Gharehdaghi]]></dc:creator>
            <pubDate>Tue, 07 Jun 2016 21:19:40 GMT</pubDate>
            <atom:updated>2016-06-07T21:19:40.991Z</atom:updated>
            <content:encoded><![CDATA[<p>it’s been awhile since Dagger as a Dependency Injection library is a popular and usual tool in developers toolbox. Getting familiar with all the features and use cases of this tool can help us writing cleaner codes. Multibinding is the feature which I’ve found it nice to match with some design patterns to solve problems and have better architecture.</p><p>In case you don’t use Dagger in your projects, I think it’s the time right now to start using it as soon as possible. <a href="https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2">Here you can find a good start point.</a> Here I assume that you already know how to use Dagger for normal injections.</p><h3>Set multibinding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*YtDZWu7cp0aeRSycqkJ70w.png" /></figure><p>Here as an example I’d like to implement(partially) a simple translator app which translates the texts. The app supports having different translators. To focus on the topic, I’ll try to skip the details as much as possible.</p><p>I start with writing a translator interface:</p><pre>public interface Translator {<br>    String getName();<br>    String translate(String text);<br>}</pre><p>An adapter for displaying the translators in spinner:</p><pre>public class TranslatorAdapter extends BaseAdapter {<br>    private List&lt;Translator&gt; translators = new ArrayList&lt;&gt;();<br><br>    public TranslatorAdapter(Collection&lt;Translator&gt; translators) {<br>        this.translators.addAll(translators);<br>    }<br><br>    @Override<br>    public Object getItem(int position) {<br>        return translators.get(position);<br>    }<br><br>    @Override<br>    public View getView(int position, ...) {<br>        Translator translator = translators.get(position);<br>        <em>//TODO inflate view and return</em><br>    }<br>    ...<br>}</pre><p>Usage on activity, fragment, … :</p><pre>public class TranslatorActivity extends AppCompatActivity {<br><br>    <strong>@Inject Set&lt;Translator&gt; translators;<br>    ...</strong></pre><pre>    private void initTranslatorsSpinner() {<br>        TranslatorAdapter adapter = new TranslatorAdapter(<br>                                               translators);<br>        translatorsSpinner.setAdapter(adapter);<br>    }</pre><p><strong>Note here that we don’t inject a single translator but a set of translators.</strong></p><p>Google translator:</p><pre>public class GoogleTranslator implements Translator {<br>    private static final String <em>NAME </em>= &quot;Google Translator&quot;;<br><br>    @Override<br>    public String getName() {<br>        return <em>NAME</em>;<br>    }<br><br>    @Override<br>    public String translate(String text) {<br>        //<em>TODO implement translation by Google services</em><br>    }<br>}</pre><p>And finally the @Module class:</p><pre>@Module<br>public class TranslatorsModule {<br><br>    <strong>@Provides(type = Provides.Type.<em>SET</em>)</strong><br>    @Singleton<br>    public Translator provideGoogleTranslator(){<br>        return new GoogleTranslator();<br>    }<br>}</pre><p>The only difference here (compare to a normal provider) is <strong>changing the provide type to Provides.Type.SET, which make us able to inject a set of translators.</strong></p><p>With this architecture, adding new translators are so simple and with minimum possible changes( in order to respect to the <a href="http://www.oodesign.com/open-close-principle.html">OCP</a> ). We have to <strong>only implement translator interface for the new translator and provide an instance of the new translator</strong>. Let’s implement a new translator:</p><pre>public class LongmanTranslator implements Translator {<br>    private static final String <em>NAME </em>= &quot;Longman Translator&quot;;<br><br>    @Override<br>    public String getName() {<br>        return <em>NAME</em>;<br>    }<br><br>    @Override<br>    public String translate(String text) {<br>        //<em>TODO implement translation by Longman dictionary</em><br>    }<br>}</pre><p>And add a new provider to @Module:</p><pre>@Module<br>public class TranslatorsModule {<br>    ...<br>    @P<strong>rovides(type = Provides.Type.<em>SET</em>)</strong><br>    @Singleton<br>    public Translator provideLongmanTranslator(){<br>        return new LongmanTranslator();<br>    }<br>}</pre><p>That’s it. You don’t have to change the other(UI &amp; UX) parts. This is the nice decoupling feature which Dagger presents us with.</p><h3>Map multibinding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*OwYCA9d5W_PSpKnIHV2TSA.png" /></figure><p>Here let’s assume we have an app which sells items, and in the checkout process user can select payment method to do the payment. Each payment system has its own process and calculations. But each seller supports different payment systems, for example one seller can support only credit-card, and the other can support PayPal, and Cash-On-Delivery as well. Like previous example I’ll try to skip the details, and focus and concept more.</p><p>Let’s assume that when we get one seller information by API call, we get the supporting payment systems in a json format. By having this list of payments, we can display the payment methods list on a spinner, and user will select one of them to do the payment:</p><pre>{<br>    //Seller information here<br>    ...<br>    &quot;payment_methods&quot;: [<br>        &quot;credit-card&quot;,<br>        &quot;paypal&quot;,<br>        ...<br>    ]<br>}</pre><p>For handling the payments, let’s create an interface for all handlers:</p><pre>public interface PaymentHandler {<br>    PaymentResult handlePayment(ShoppingCart cart);<br>}</pre><p>In checkout process we will have something like this:</p><pre>public class CheckoutProcess {<br><br>    <strong>@Inject Map&lt;String, PaymentHandler&gt; paymentHandlers;<br> </strong>   ...<br>    private void onCheckout() {<br>        ...<br>        doPayment(selectedPaymentMethod);<br>    }<br>    <br>    private void doPayment(String selectedPaymentMethod) {<br>        PaymentHandler paymentHandler =<br>                        paymentHandlers.get(selectedPaymentMethod);<br>        paymentHandler.handlePayment(shoppingCart);<br>    }<br>}</pre><p>Note that we use a Map for mapping the payment methods names we get from seller information API to PaymentHandler. Let’s implement credit card payment handler:</p><pre>public CreditCardPaymentHandler implements PaymentHandler {</pre><pre>    @Override<br>    PaymentResult handlePayment(ShoppingCart cart){<br>        //TODO here is all the bussiness logic for handling the<br>        //credit card payment method<br>    }</pre><pre>}</pre><p>Provider in @Module class:</p><pre>@Module<br>public class PaymentModule {<br><br>    <strong>@Provides(type = Provides.Type.<em>MAP</em>)<br>    @StringKey(&quot;credit-card&quot;)</strong><br>    public PaymentHandler provideCreditCardPaymentHandler(){<br>        return new CreditCardPaymentHandler();<br>    }<br>}</pre><p><strong>We should use Provides.Type.<em>MAP as provider type, and because Dagger wants to know what is the key for injecting into a Map in compile time, we should use @StringKey annotation to specify that.</em></strong></p><p>if the map we’re going to inject to has different type of key we can use @IntKey, @LongKey, @ClassKey. For more specific map key types(e.g. enum, …) we can use @MapKey and create a new annotation for that. I’m not going to go into more details for this now.</p><p>With this architecture, if in the future we decide to add a new payment system <strong>we only have to add a new handler and provide that for injection. Let’s add a paypal payment handler</strong>:</p><pre>public PaypalPaymentHandler implements PaymentHandler {</pre><pre>@Override<br>    PaymentResult handlePayment(ShoppingCart cart){<br>        //TODO here is all the bussiness logic for handling the<br>        //PayPal payment method.<br>    }</pre><pre>}</pre><p>And provide it in @Module class:</p><pre>@Module<br>public class PaymentModule {<br>    ...<br>    <strong>@Provides(type = Provides.Type.<em>MAP</em>)<br>    @StringKey(&quot;paypal&quot;)</strong><br>    public PaymentHandler providePayPalPaymentHandler(){<br>        return new PaypalPaymentHandler();<br>    }<br>}</pre><h3>Conclusion</h3><p>I tried to just explain the concepts and skip the implementation details by simplifying the examples as much as possible. For finding more details please take a look at <a href="http://google.github.io/dagger/multibindings.html">the dagger documentation.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=713254b7f734" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending objects to Fragment; Naive question: is it sent by value?!]]></title>
            <link>https://medium.com/@hamidgh/sending-objects-to-fragment-naive-question-is-it-sent-by-value-ddaaa19fa42d?source=rss-156639da0783------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddaaa19fa42d</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Hamid Gharehdaghi]]></dc:creator>
            <pubDate>Sun, 27 Dec 2015 13:20:36 GMT</pubDate>
            <atom:updated>2015-12-27T13:21:46.506Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>1. Introduction</strong></h4><p>if you have written application in Android, you know <a href="http://developer.android.com/reference/android/content/Intent.html">Intent</a> and <a href="http://developer.android.com/reference/android/os/Bundle.html">Bundle</a> which we use to send some extra data to Android application components(Activities, Services, …). Intent use Bundle internally to hold the extras. so Bundle is the key class for holding the extras.</p><p>You can put primitive types, and objects into Bundle. But for putting objects, your class has to implement either Serializable or Parcelable interfaces, and as you know, good developers prefer Parcelable because of performance.</p><p>We’re not going to go into the details of how you should implement these interfaces as there’re lots of articles out there which can explain it perfectly. In addition there’s a good <a href="https://github.com/mcharmas/android-parcelable-intellij-plugin">plugin for Android Studio</a> which can ease the pain of implementing Parcelable interface.</p><h4>2. How does Bundle work?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*JDmr0Xp8d7TgYe9RbXYfvg.png" /></figure><p>Bundle uses a <a href="http://developer.android.com/reference/java/util/Map.html">Map</a>&lt;String, Object&gt; for holding the extras you’re putting into. so in this way there’s no difference between a Map and Bundle. but when you’re going to send data to another Activity(or any other IPC components such as Service, BroadcastReceiver,…) the Map will be marshalled into byte[] via a Parcel, and will send to destination. in destination the data will go into the same flow in reverse and the byte[] will be unmarshalled into Map&lt;String,Object&gt; and you can have extras by providing the same keys.</p><p>So Bundle is like a Map which can also be marshalled/unmarshalled to/from byte[]. one important note is that you cannot use this byte[] to persist your bundle, as it’s designed <strong>ONLY </strong>to transfer to components, and will not work if underlying data structure changes.</p><h4>3. Naive question: Will objects be sent to Fragments by value?</h4><p><strong>Sending object to Activity:</strong></p><pre>Product myproduct = ...</pre><pre>Intent intent = new Intent(context, ProductDetails.class);<br>intent.putExtra(&quot;product&quot;, myproduct);<br>startActivity(intent);</pre><p>When you’re sending objects to another Activity(via Intent), as the communication with Activities(and also BroadcastReceivers, Services, …) are IPC, so Bundle(which is inside the Intent) will be marshalled into byte[]. so in the destination you will have <strong>NEW </strong>objects with the same content everytime.</p><p>For writing to and reading from Parcel, Parcelable.write and Parcelable.CREATOR.ceateFromParcel are called in this situation.</p><p><strong>Sending object to Fragment:</strong></p><pre>Product myproduct = ...</pre><pre>Bundle args = new Bundle();<br>args.putParcelable(&quot;product&quot;, myproduct);<br>Fragment productDetailsFragment = new ProductDetailsFragment();<br>productDetailsFragment.setArguments(args);<br>...</pre><p>When you’re putting objects into Bundle to send to Fragment(as an argument), the objects are held in the internal map of Bundle. but because sending arguments to Fragments is not an IPC process, so it doesn’t need to be marshalled to byte[], and Fragment will get the <strong>SAME </strong>object you’re sending from Activity from the internal map!!! so if you change the object, you will get the changes also in your Activity because they’re actually one object.</p><p><em>But what if the fragment is going to be destroyed and created again due to memory lackage by Android?</em> in this case the Bundle will be marshalled and its byte[] will be persist until it is created again, and then the Bundle will be created by unmarshalling the saved byte[]. so a <strong>NEW </strong>object will be created for Fragment, and it’s not the same object from Activity.</p><p><strong>Sum up: </strong>As you can see, sending objects to an Activity are by value. but for Fragments they’re passed sometimes by reference and sometimes by value. so you should always consider this and never rely on the references.</p><p>One workaround for this problem is making it identical in all situations. for this you can send a copy of your objects to Fragment and not the objects themselves. there’re some ways to do that, but one of the easiest(&amp;fast) ways is implementing Clonable interface and using Parcel to clone your object:</p><pre>public class <strong>Product</strong> implements <strong>Parcelable</strong>, <strong>Cloneable </strong>{</pre><pre>    @Override<br>    public Object clone() {<br>        Parcel parcel = Parcel.<em>obtain</em>();<br>        this.writeToParcel(parcel, 0);<br>        byte[] bytes = parcel.marshall();<br><br>        Parcel parcel2 = Parcel.<em>obtain</em>();<br>        parcel2.unmarshall(bytes, 0, bytes.length);<br>        parcel2.setDataPosition(0);<br>        return Product.<em>CREATOR</em>.createFromParcel(parcel2);<br>    }</pre><pre>    //Parcelable implementation code here ...</pre><pre>}<br></pre><pre>Product myproduct = ...</pre><pre>Bundle args = new Bundle();<br>args.putParcelable(&quot;product&quot;, (Product)myproduct.clone());<br>Fragment productDetailsFragment = new ProductDetailsFragment();<br>productDetailsFragment.setArguments(args);</pre><p>Here it’s assumed that you’ve implemented Parcelable in all your models classes, so you can use this method to deep-clone your object.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddaaa19fa42d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>