<?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 Fernando Sierra on Medium]]></title>
        <description><![CDATA[Stories by Fernando Sierra on Medium]]></description>
        <link>https://medium.com/@fernandosierra?source=rss-11244b33cdf8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*FcVeMD1QW7QSsbi9e63myg.jpeg</url>
            <title>Stories by Fernando Sierra on Medium</title>
            <link>https://medium.com/@fernandosierra?source=rss-11244b33cdf8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 05:45:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fernandosierra/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[Android Support Annotations]]></title>
            <link>https://medium.com/@fernandosierra/android-support-annotations-331d925ab26c?source=rss-11244b33cdf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/331d925ab26c</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[annotations]]></category>
            <dc:creator><![CDATA[Fernando Sierra]]></dc:creator>
            <pubDate>Fri, 11 Mar 2016 15:32:23 GMT</pubDate>
            <atom:updated>2016-03-11T17:11:33.472Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>Android has grown since it saw the light on 2007; Development and tools grew at the same rate. Now we have Android Studio, Gradle, and Android Developer Tools, being the latter perhaps the least known of them.</p><p><strong>Android Support Annotations</strong> were introduced on <em>version</em> <em>19.1</em> of the <strong>Android Support Library, </strong>in <em>version 22.2</em> more useful tools were introduced.</p><p>Using annotations will provide us the capability to avoid bugs when we are writing code. These annotations are checked by lint, if we are having some troubles or we are violating a rule defined by an annotation, lint will notify us with a warning.</p><h3>Integrating Annotations</h3><p>First of all, we need to add the library to our project.</p><h4>Adding Support Annotations into our project</h4><p>The library is shipped individually, as all the support libraries (appcompat, cardview, recyclerview, etcetera). If you are using appcompat, you are ready to use annotations, because appcompat depends on it.</p><p>To manually add the library into our project, we just need to add the next line in our gradle’s dependencies:</p><pre>compile &#39;com.android.support:support-annotations:23.2.0&#39;</pre><p>After sync our project with gradle files, we will have available all the annotations.</p><p>Now we are ready to use annotations into our project; We have several annotations, but we can group them by functionality or goal.</p><h3>Nullness/Nullity</h3><p>The nullness annotations perhaps are the most famous, basically these annotations are used to indicate if a value can be <em>null</em> or <em>not</em>. This is useful when we are defining component behaviours.</p><h4><strong><em>@NonNull</em></strong></h4><p>This annotation indicates that a parameter, attribute, or return value <strong>NEVER</strong> will be <em>null</em>, this reduces the null-checks on our code, and reduces our <a href="https://en.wikipedia.org/wiki/Cyclomatic_complexity">cyclomatic complexity</a>.</p><pre><strong>@NonNull</strong><br>public static String buildUrl(<strong>@NonNull</strong> String endpoint) {<br>    return BASE_URL + endpoint;<br>}</pre><h4><strong><em>@Nullable</em></strong></h4><p>This annotation <em>isn’t the opposite</em> of his sibling (the opposite would be: always be null, and that… is useless), this annotation indicates if a parameter, attribute, or return value <strong>CAN</strong> be null. This provides us the certitude where we need to add null-checks.</p><pre><strong>@Nullable</strong><br>public String getPhoneNumber(){<br>    TelephonyManager telManager =<br>              (TelephonyManager)getSystemService(TELEPHONY_SERVICE);<br>    return telManager.getLine1Number();<br>}</pre><h3>Resource Type</h3><p>Android development is all about resources, we use them for everything: to put a fancy Activity’s background, to put a <em>String</em> indicating a button’s action, to give the <em>size</em> to our text fields and more.</p><p>As we know all those resources are indexed in our <a href="http://developer.android.com/intl/es/guide/topics/resources/accessing-resources.html">R class</a>, when we are working with resources on code, we can have troubles trying to indicate what kind of resource we need on a method, because all the resources are represented by a Integer value. We can solve it in many ways, but my favourite is using <em>Resource Type Annotations</em>.</p><p>We have an annotation for each Android resource type, so for <em>String</em> resources we have <strong>@StringRes</strong>, for <em>Drawables</em> we have <strong>@DrawablesRes</strong>, for <em>Colours</em> we have <strong>@ColorRes</strong>, etcetera. All the <em>Resource Type</em> annotations follow the same name pattern: <em>Resource type followed by “Res”</em>.</p><p>Those annotations give us the capability to know exactly what type of resource we are waiting, if we pass a wrong type, then lint will notify us with a warning.</p><pre><strong>@NonNull</strong><br>public View inflateItemView(<strong>@NonNull</strong> Context context,<br>                            <strong>@NonNull</strong> ViewGroup parent,<br>                            <strong>@LayoutRes</strong> int layout,<br>                            <strong>@ColorRes</strong> int textColor,<br>                            <strong>@DrawableRes</strong> int icon){<br>    View root = LayoutInflater.from(context)<br>                .inflate(layout, parent, false);<br>    TextView title = (TextView)root.findViewById(R.id.text_title);<br>    ImageView headerIcon = (ImageView)root.findViewById(R.id.icon);<br>    title.setTextColor(ContextCompat.getColor(context, textColor));<br>    headerIcon.setImageResource(icon);<br>}</pre><p>Additionally we have a special <em>Resource Type</em> annotation called @<strong>AnyRes</strong>, which is to indicate we are requiring a resource, no matter what type, it just needs be an Android resource indexed in R class.</p><h3>Typedef</h3><p>Perhaps my favourite annotation, this one was created specifically to substitute <strong>Java’s Enums</strong> in our Android code. Why would we want to replace the <em>Enums</em> in our code? Perhaps you would like to see the next video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHzs6OBcvNQE%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHzs6OBcvNQE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHzs6OBcvNQE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/554d2e7f0c488754a59fad710a06d84f/href">https://medium.com/media/554d2e7f0c488754a59fad710a06d84f/href</a></iframe><p>Now we know why we would like to avoid <em>Enums</em>, but they are very useful when we are writing our code, they provide encapsulation, order, and make our code clearer. As <a href="https://medium.com/u/6e1a63c4fcd1">Colt McAnlis</a> taught us in the video, we can use <em>Typedef annotations </em>instead of<em> Enums</em>.</p><p>We can define Integer and String <em>“healthy Enums”</em> using <em>Typedef</em> annotations, those will be conformed by three parts: <strong>Values Definition</strong>, <strong>Retention</strong> and <strong>Interface Definition.</strong></p><h4>Values Definition</h4><p>First of all, we need to define which values will be part of our new type.</p><pre>public static final int SINGLE_FLIGHT = 1;<br>public static final int ROUND_FLIGHT = 2;<br>public static final int MULTI_FLIGHT = 3;</pre><pre><strong>@IntDef({SINGLE_FLIGHT, ROUND_FLIGHT, MULTI_FLIGHT})</strong></pre><h4>Retention</h4><p>We grouped the values we wanted, then we will define the retention of the new type. The retention tell to the compiler the part of the compilation we want the new type to reach.</p><p>We can choose between <strong>CLASS</strong>, <strong>RUNTIME</strong> and <strong>SOURCE</strong>, each one is defined in <a href="http://developer.android.com/intl/es/reference/java/lang/annotation/RetentionPolicy.html">RetentionPolicy</a>. The most common is <strong>SOURCE</strong>, because most of the time, we want those types only to be available for us, when we are writing code. On the other hand, if we are writing a library, it’s possible we want to use <strong>CLASS</strong> or <strong>RUNTIME</strong>, it will depend on our requirements.</p><pre>public static final int SINGLE_FLIGHT = 1;<br>public static final int ROUND_FLIGHT = 2;<br>public static final int MULTI_FLIGHT = 3;</pre><pre>@IntDef({SINGLE_FLIGHT, ROUND_FLIGHT, MULTI_FLIGHT})<br><strong>@Retention(RetentionPolicy.SOURCE)</strong></pre><h4>Interface Definition</h4><p>Finally, we only need to give a name to our new type.</p><pre>public static final int SINGLE_FLIGHT = 1;<br>public static final int ROUND_FLIGHT = 2;<br>public static final int MULTI_FLIGHT = 3;</pre><pre>@IntDef({SINGLE_FLIGHT, ROUND_FLIGHT, MULTI_FLIGHT})<br>@Retention(RetentionPolicy.SOURCE)<br><strong>public @interface FlightType {}</strong></pre><h4>Use</h4><p>We defined our new type, we put a source retention policy, and we gave it a name; Now it’s time to use it in our code.</p><pre>public static final int SINGLE_FLIGHT = 1;<br>public static final int ROUND_FLIGHT = 2;<br>public static final int MULTI_FLIGHT = 3;</pre><pre><strong>@IntDef({SINGLE_FLIGHT, ROUND_FLIGHT, MULTI_FLIGHT})<br>@Retention(RetentionPolicy.SOURCE)<br>public @interface FlightType {}</strong></pre><pre>private <strong>@FlightType</strong> int mFlightType;</pre><pre>public void setFlightType(<strong>@FlightType</strong> int flightType){<br>    this.mFlightType = flightType;<br>}</pre><p>Now when we try to set a value which isn’t component of the new type, lint will notify us about this issue with an error.</p><h3>Threading</h3><p>Since a few years ago, Android Applications started to grow in complexity and content, today almost all of them use Internet and Databases intensively.</p><p>In the <a href="http://developer.android.com/intl/es/training/articles/perf-anr.html">Android Developer Web</a> we can read about how to make our apps responsive, and how to avoid UI freezes or ANRs (Application Not Responding).</p><p>When we are working with multitasking on Android, we can have troubles if we perform View tasks in a different Thread than MainThread/UIThread. We can save time and headaches, when we are identifying possible violations to that restriction if we use <em>Threading Annotations</em>.</p><p>There are four Threading Annotations: <strong>@UiThread</strong>, <strong>@MainThread</strong>, <strong>@WorkerThread</strong> and <strong>@BinderThread</strong>. If a restriction is violated, lint will notify us with an error message.</p><h4>@UiThread/MainThread</h4><p>When we annotate a method or class with these, we can only write <strong>view</strong> and/or <strong>life-cycle</strong> code inside that method.</p><p>They can seem as the same Thread, but that isn’t true. Below is the explanation about this extracted from the<a href="http://tools.android.com/tech-docs/support-annotations"> Support Annotations Documentation</a>.</p><blockquote>There is one and only one main thread in the process. That’s the @MainThread. That thread is <strong>also</strong> a @UiThread. This thread is what the main window of an activity runs on, for example. However it is also possible for applications to create other threads on which they run different windows. This will be very rare; really the main place this distinction matters is the system process. Generally you’ll want to annotate methods associated with the life cycle with @MainThread, and methods associated with the view hierarchy with @UiThread. Since the @MainThread is a @UiThread, and since it’s usually the case that a @UiThread is the @MainThread, the tools (lint, Android Studio, etc) treat these threads as interchangeable, so you can call @UiThread methods from @MainThread methods and vice versa.</blockquote><pre><strong>@MainThread</strong><br>public void navigateToSettings() {<br>    Intent intent = new Intent(this, SettingsActivity.class);<br>    startActivity(intent);<br>    finish();<br>}</pre><pre><strong>@UiThread</strong><br>public void initializeView(){<br>    EditText editName = findViewById(R.id.edit_name);<br>    Button btnNext = findViewById(R.id.btn_next);<br>    editName.setTypeface(AppFonts.getInstance().getRegular());<br>    btnNext.setTypeface(AppFonts.getInstance().getBold());<br>    btnNext.setOnClickListener(this);<br>}</pre><h4>@WorkerThread</h4><p>We annotate a method or class with this to indicate it <strong>MUST</strong> be executed on a different thread than <em>Main/UI Thread</em>. If we try to execute the annotated code on the <em>Main Thread</em>, lint will notify us about the violation with an error.</p><pre><strong>@WorkerThread<br>@NonNull<br></strong>public List&lt;Message&gt; getMessages(){<br>    List&lt;Message&gt; messages = new LinkedList&lt;&gt;();<br>    Response response = NetRepository.getInstance().getMessages();<br>    if(response.error != null){<br>       parseMessages(response.body, messages);<br>    }<br>    return messages;<br>}</pre><h4>@BinderThread</h4><p>Android is based on Linux (as we know), but Android contains some features and modifications to make it runnable on Mobile Devices, one of them is <strong>Binder</strong>.</p><p>Everything in Linux (and Android) is a process, the hardware services (like Location, Camera, WiFi, etcetera) are a process too, therefore our application is another process running. The problem is: how will we intercommunicate these running processes?</p><p>With <strong>Binder</strong>.</p><p><strong>Binder</strong> performs all the low-level calls necessary to intercommunicate processes through the Kernel; The Android SDK gives us the capability to write our own <em>Binder</em> code through <a href="http://developer.android.com/intl/es/reference/android/os/IBinder.html">IBinder</a>.</p><p>When we are writing our app, sometimes we use <em>ContentProviders</em>, this is a great example of where we use <strong>Binder</strong>. A <em>ContentProvider</em> is used to expose information to another application, as we already know, each app is a different process, when we request some information or we want to modify information through a <em>ContentProvider</em>, we are using <strong>Binder</strong>.</p><p><a href="http://www.cubrid.org/blog/dev-platform/binder-communication-mechanism-of-android-processes/">Here</a> you can read a wonderful explanation of what <strong>Binder</strong> is and how it works.</p><p>A good place to put a <strong>@BinderThread</strong> annotation is a method/class who will be called by a <em>ContentProvider</em>.</p><pre><strong>@BinderThread<br>@Nullable</strong><br>public Cursor getMessages(String[] projection,<br>                          String selection,<br>                          String[] selectionArgs,<br>                          String sortOrder)throws SQLiteException {<br>    SQLiteDatabase database = mHelper.getWriteableDatabase();<br>    Cursor cursor = database.query(MESSAGES_TABLE,<br>                                   projection,<br>                                   selection,<br>                                   selectionArgs,<br>                                   null,<br>                                   null,<br>                                   sortOrder);</pre><pre>    return cursor;<br>}</pre><h4>RGB Color Integers</h4><p>We saw the <em>Resource Type</em> annotations, and we know there’s an specific annotation for <em>Colour Resources</em> (<strong>@ColorRes</strong>), but sometimes we need to use a <em>RGB/ARGB</em> colour integer and the game changes. This can produce a very common mistake when we are writing our code, because sometimes a method only ask for an <em>int</em> as input, but we don’t know if it needs a resource id or an integer colour. To avoid these mistakes, we can use the <strong>@ColorInt</strong> annotation.</p><pre>public void setFilter(<strong>@ColorInt</strong> int color) {<br>    this.mFilter = color;<br>}</pre><p>Now when we pass a resource id, lint will notify us about the problem with an error and a fancy suggestion about how can we make it correctly.</p><p>That’s all for now, we have some other annotations to see, but I will cover them on a second part.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=331d925ab26c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>