/
feed.xml
232 lines (143 loc) · 123 KB
/
feed.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Curious Techizen</title>
<description>A place for discussing anything tech. Old and new. Experiences and Opinions. Questions and rants. Primarily programming-related, but not exclusively.</description>
<link>/blog/</link>
<atom:link href="/blog/feed.xml" rel="self" type="application/rss+xml" />
<pubDate>Wed, 12 Aug 2015 23:34:27 +0530</pubDate>
<lastBuildDate>Wed, 12 Aug 2015 23:34:27 +0530</lastBuildDate>
<generator>Jekyll v2.5.3</generator>
<item>
<title>AO(sp)y Part 1</title>
<description><p>This post is the first in a series (hopefully) in which I spy on AOSP (hence the title - yes, I know I&#39;m not winning any prizes for creative blog post titles!) and try to gather glimpses of what&#39;s coming to the world of Android.</p>
<blockquote>
<p><strong>Disclaimer:</strong> Most of this is guess work. In many cases I&#39;m not even looking at any code - the commit messages and review comments are as far I go. Do not make any decisions based on this post!</p>
</blockquote>
<p>In this first episode, we will look at improvements coming to Android Studio (most probably in 1.4)</p>
<h3>Material Icon Picker</h3>
<p>There <a href="https://plugins.jetbrains.com/plugin/7647?pr=androidstudio">already exist</a> plugins for Android Studio that make it easy for you to include Material Design icons in your project. Google is <a href="https://android-review.googlesource.com/#/c/155698/">working on</a> bringing something similar into the Android Studio.</p>
<p>Now, I haven&#39;t actually checked out this code and built it so I don&#39;t know what the picker actually looks like, but it would be a safe bet to assume that it&#39;ll be integrated into the existing &quot;Asset Studio&quot; (which itself started as a web app, then found its way into Eclipse and in its current avatar, it is part of AS).</p>
<h3>Material Color Suggestor</h3>
<p>If I want to change the color palette of my app today, I need to go to <a href="http://www.materialpalette.com/">http://www.materialpalette.com/</a> and choose my colors there and finally download the styles.xml file. <a href="https://android-review.googlesource.com/#/c/156624/">This feature</a> will make it easy for you to set your material color palette from within Android Studio. Moreover, the tool is a color suggestor - you choose a primary color and AS will suggest a primaryDark and an accent color that goes with it according to the material design specs.</p>
<h3>Import SVG as Vector Drawable</h3>
<p>Again, there <a href="http://inloop.github.io/svg2android/">already exist</a> tools to convert an SVG file into an Android-compatibe Vector Drawable, but it would be nice to have <a href="https://android-review.googlesource.com/#/c/163309/">this functionality</a> right in Studio.</p>
<h3>VectorDrawable to PNG</h3>
<p>This is not an Android Studio feature - rather it is a <a href="https://android-review.googlesource.com/#/c/162815/">Gradle feature</a>. It will convert vector drawables into PNGs for use with pre-Lollipop. This will be done at build time. I&#39;m not sure if this means that we can do away with creating those <code>drawable-*hdpi</code> PNGs altogether though.</p>
<h3>New Layout Editor</h3>
<p>There is a <a href="https://android-review.googlesource.com/#/c/159435/">large list of commits</a> mentioning the &quot;Nele&quot; which seems to be an internal acronym for New Layout Editor. A cursory glance at it did not reveal much about what exactly is new in this layout editor. However, it is possible that this info is there buried somewhere in one of the 49 related commits and that I have missed it. One thing is for sure - this is a pretty big change and Google wouldn&#39;t have embarked on it if it wouldn&#39;t bring significant advantages to developers.</p>
<h3>AppBar creation in AS</h3>
<p>Android Studio is <a href="https://android-review.googlesource.com/#/c/162681/">gaining the capability</a> to include an AppBar when you use the templates to create a new Activity. According to the commit message, this will be optional. Also, a dependency on the design support library will be included by default for new projects. This is a very welcome change.</p>
<p>Stay tuned for Part 2 where we go beyond the IDE and dig a little deeper into the toolchain.</p>
</description>
<pubDate>Wed, 12 Aug 2015 00:00:00 +0530</pubDate>
<link>/blog/2015/08/12/ao-spy-1/</link>
<guid isPermaLink="true">/blog/2015/08/12/ao-spy-1/</guid>
<category>aosp</category>
<category>studio</category>
<category>android</category>
</item>
<item>
<title>Nested Fragments and the Backstack - Part 3</title>
<description><p>This is the third post in the series about Nested Fragments and the Back Stack in Android. Read the previous posts here:</p> <ol><li><a href="http://curioustechizen.blogspot.com/2014/01/nested-fragments-and-back-stack.html">Part 1</a></li><li><a href="http://curioustechizen.blogspot.com/2014/02/nested-fragment-and-backstack-part-2.html">Part 2</a></li></ol> <p>The first two posts have looked at the topic taking <code>ViewPager</code> as an example. I have also mentioned repeatedly that this is not the only use case for having to maintain the back-stack of nested fragments. One use case that I threw up often in comments was about <strong>Navigation Drawers</strong>. That is exactly what this post will look into.</p> <hr><p><strong>EDIT: Some Google engineers, including the creators of the Android framework have expressed their reservations regarding this article. Read <a href="https://plus.google.com/100961288997176421259/posts/BLLi6srFtwT">this G+ thread</a> for more details. They point out that using an <code>Application</code> sub-class to save state is not a good idea, but also that saving <code>Fragment</code> instance state explicitly might in itself needs to be considered carefully. I hope to gather their thoughts and write a follow-up post in the coming weeks. Stay Tuned.</strong></p><hr> <h3 id="re-cap">Re-cap</h3> <p>Just to re-cap the conclusion from the previous article:</p> <ul><li>Consider pro-actively saving your <code>Fragment</code> states in <code>onPause</code>, particularly is the <code>Fragment</code> happens to nest other fragments inside of it. </li><li>Do not rely solely on the system saving state for you in <code>onSaveInstanceState</code>.</li><li>Use <code>FragmentManager#saveFragmentInstanceState</code> to save the Fragment state including the back-stack of nested fragment transactions for you.</li><li>Do not hold on to the saved state any longer than necessary.</li></ul> <h3 id="adapting-to-navigation-drawer">Adapting to Navigation Drawer</h3> <p>If you take the <a href="https://github.com/curioustechizen/blog-nested-fragments-backstack/tree/master/nested-fragments-backstack-part2">source code for Part 2</a> of the series, and adapt it as-is to a Navigation Drawer example, you’ll find that things don’t quite work as you’d expect. In particular, you’ll find that <em>even though you have saved the state of the <code>ContainerFragment</code> in <code>onPause</code></em>, the next time you return to this fragment, its state is cleared. </p> <p>Why is this? The alert reader might have spotted the reason.</p> <p>In the case of the <code>ViewPager</code> example, we clear the saved fragment state in <code>onDestroy()</code>. This is because of the way ViewPager works (or rather, <code>FragmentPagerAdapter</code> or <code>FragmentStatePagerAdapter</code> works): When you navigate away from a tab, the Fragment’s <code>`onPause</code> is called but none of the other life-cycle methods are called. This means <code>onDestroy</code> is skipped and the Fragment is simply torn down. <code>onDestroy</code> is only called when the hosting <code>Activity</code> is destroyed.</p> <pre style="" class="prettyprint prettyprinted"><code class="language-java"><span class="pln"> </span><span class="lit">@Override</span><span class="pln"><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> onPause</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> </span><span class="kwd">super</span><span class="pun">.</span><span class="pln">onPause</span><span class="pun">();</span><span class="pln"><br /> </span><span class="pun">((</span><span class="typ">NestedFragApp</span><span class="pun">)</span><span class="pln">getActivity</span><span class="pun">().</span><span class="pln">getApplication</span><span class="pun">()).</span><span class="pln">setFragmentSavedState</span><span class="pun">(</span><span class="pln">SAVED_STATE_KEY</span><span class="pun">,</span><span class="pln"> getFragmentManager</span><span class="pun">().</span><span class="pln">saveFragmentInstanceState</span><span class="pun">(</span><span class="kwd">this</span><span class="pun">));</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /><br /> </span><span class="lit">@Override</span><span class="pln"><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> onDestroy</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> </span><span class="kwd">super</span><span class="pun">.</span><span class="pln">onDestroy</span><span class="pun">();</span><span class="pln"><br /> </span><span class="pun">((</span><span class="typ">NestedFragApp</span><span class="pun">)</span><span class="pln">getActivity</span><span class="pun">().</span><span class="pln">getApplication</span><span class="pun">()).</span><span class="pln">setFragmentSavedState</span><span class="pun">(</span><span class="pln">SAVED_STATE_KEY</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">);</span><span class="pln"><br /> </span><span class="pun">}</span></code></pre> <p>However, when you use a Navigation Drawer, the case is different. In this situation, there is no <code>PagerAdapter</code> to deal with. When you navigate from one item in the navigation drawer to another, the “old” Fragment undergoes the complete life-cycle - <code>onPause</code> all the way to <code>onDestroy</code> and <code>onDetach</code>. As a consequence, since you’re clearing the saved Fragment state in <code>onDestroy</code> of the <code>ContainerFragment</code>, <strong>you end up clearing the state that you had just saved in <code>onPause</code></strong>.</p> <h3 id="solution">Solution?</h3> <p>Well, the solution is rather simple - just don’t clear the state in <code>onDestroy</code> of the parent Fragment! In addition, there are a few other minor changes - like the way you set the initial state of the ContainerFragment (instead of retrieving the saved state in one of the life cycle methods of the Fragment, you use <code>setInitialSavedState</code> in the static creator method). The source code for this is available at the <a href="https://github.com/curioustechizen/blog-nested-fragments-backstack">github repo</a> for this series.</p> <pre style="" class="prettyprint prettyprinted"><code class="language-java"><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">static</span><span class="pln"> </span><span class="typ">ContainerFragment</span><span class="pln"> newInstance</span><span class="pun">(</span><span class="typ">SavedState</span><span class="pln"> savedState</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> </span><span class="typ">ContainerFragment</span><span class="pln"> frag </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">ContainerFragment</span><span class="pun">();</span><span class="pln"><br /> frag</span><span class="pun">.</span><span class="pln">setInitialSavedState</span><span class="pun">(</span><span class="pln">savedState</span><span class="pun">);</span><span class="pln"><br /> </span><span class="kwd">return</span><span class="pln"> frag</span><span class="pun">;</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /> </span><span class="pun">...</span><span class="pln"><br /> </span><span class="pun">...</span><span class="pln"><br /> </span><span class="lit">@Override</span><span class="pln"><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> onPause</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> </span><span class="kwd">super</span><span class="pun">.</span><span class="pln">onPause</span><span class="pun">();</span><span class="pln"><br /> </span><span class="pun">((</span><span class="typ">NestedFragApp</span><span class="pun">)</span><span class="pln">getActivity</span><span class="pun">().</span><span class="pln">getApplication</span><span class="pun">()).</span><span class="pln">setFragmentSavedState</span><span class="pun">(</span><span class="pln">SAVED_STATE_KEY</span><span class="pun">,</span><span class="pln"> getFragmentManager</span><span class="pun">().</span><span class="pln">saveFragmentInstanceState</span><span class="pun">(</span><span class="kwd">this</span><span class="pun">));</span><span class="pln"><br /> </span><span class="pun">}</span></code></pre> <p>Here’s a video showing this in action (Unfortunately the Android screenrecord tool doesn’t like it if you rotate the device during the recording, but I think the video demnostrates the point sufficiently):</p> <iframe src="//www.youtube.com/embed/JEzerV4Ee_g" allowfullscreen="" height="315" width="420" frameborder="0"></iframe><div class="se-section-delimiter"></div> <h3 id="forgetting-the-saved-state">Forgetting the saved state?</h3> <p>The bullet points that we established in the previous post (re-capped at the beginning of this post) say that you should not hold on to the saved state any longer than necessary. However, we had to violate that rule in this solution because - well - it is pointless to save the state only to immediately clear it!</p> <p>However, depending on your use case you might approach this in a different manner. For example, you might only clear the fragment saved state when the hosting <code>Activity</code> is destroyed. This is <em>not</em> demonstrated in the sample code on github but should be straightforward to implement.</p></description>
<pubDate>Sun, 09 Feb 2014 12:26:00 +0530</pubDate>
<link>/blog/2014/02/09/nested-fragments-and-backstack-part-3/</link>
<guid isPermaLink="true">/blog/2014/02/09/nested-fragments-and-backstack-part-3/</guid>
<category>nested</category>
<category>fragments</category>
<category>programming</category>
<category>backstack</category>
<category>android</category>
</item>
<item>
<title>Nested Fragment and the BackStack - Part 2</title>
<description><p>This article is the second in this series about Nested Fragments and the Back Stack in Android. You can read Part 1 <a href="http://curioustechizen.blogspot.com/2014/01/nested-fragments-and-back-stack.html">here</a>. To get this post into context, take a look at the video embedded in the previous post, if nothing else.</p> <p><strong>Edit: Later posts in this series at</strong></p><ol><li><a href="http://curioustechizen.blogspot.com/2014/02/nested-fragments-and-backstack-part-3.html">Part 3</a></li></ol> <hr><p><strong>EDIT: Some Google engineers, including the creators of the Android framework have expressed their reservations regarding this article. Read <a href="https://plus.google.com/100961288997176421259/posts/BLLi6srFtwT">this G+ thread</a> for more details. They point out that using an <code>Application</code> sub-class to save state is not a good idea, but also that saving <code>Fragment</code> instance state explicitly might in itself needs to be considered carefully. I hope to gather their thoughts and write a follow-up post in the coming weeks. Stay Tuned.</strong></p><hr> <p>At the risk of sounding repetitive, I’ll start off this post by once again stating the gist of the previous post:</p> <blockquote> <p>A Fragment’s <code>onSaveInstanceState</code> method is not guaranteed to be called when it is “removed”. The <code>Fragment</code> might simply be torn down. The only time its state might be saved is when the hosting <code>Activity</code> saves its state.</p></blockquote> <p>We also saw how this could be a problem when you use nested fragments and a <code>FragmentManager</code> doesn’t save its backstack of fragment transactions. In this part, we’ll look at one possible solution to this problem.</p><div class="se-section-delimiter"></div> <h3 id="save-state-in-onpause">Save state in onPause</h3> <p>This is the obvious solution to the problem. The Android docs also state this time and again: it is a best practice to proactively save state. Also, since <code>onPause</code> is the only callback that is guaranteed to be called, it makes sense to save your instance state here.</p> <p>Having said that, it is easy to save view states, scroll positions and even entire arbitrary objects in <code>onPause.</code> But, how does one save a back stack of fragment transactions?</p> <p>Enter <a href="http://developer.android.com/reference/android/support/v4/app/Fragment.SavedState.html"><code>Fragment.SavedState</code></a>. You can ask the <code>FragmentManager</code> to save the state of a <code>Fragment</code> using <a href="http://developer.android.com/reference/android/support/v4/app/FragmentManager.html#saveFragmentInstanceState%28android.support.v4.app.Fragment%29"><code>saveFragmentInstanceState</code></a>. The back stack being managed by a Fragment’s nested <code>FragmentManager</code> is included in the state saved by this method.</p> <h4 id="the-application-sub-class">The <code>Application</code> sub-class</h4> <p>This post shows how you could use a sub-class of the <code>Application</code> class to save the state, but you might choose another mechanism to do so. The important thing is that the state has to be saved. We use a <code>Map</code> of strings as keys and the saved state as values in this example.</p> <pre class="prettyprint"><code>public class NestedFragApp extends Application {<br /><br /> Map&lt;String, Fragment.SavedState&gt; savedStateMap;<br /><br /> @Override<br /> public void onCreate() {<br /> savedStateMap = new HashMap&lt;String, Fragment.SavedState&gt;();<br /> super.onCreate();<br /> }<br /><br /> public void setFragmentSavedState(String key, Fragment.SavedState state){<br /> savedStateMap.put(key, state);<br /> }<br /><br /> public Fragment.SavedState getFragmentSavedState(String key){<br /> return savedStateMap.get(key);<br /> }<br /><br />}<br /></code></pre> <h4 id="explicitly-saving-fragment-state">Explicitly saving Fragment state</h4> <p>Then, you save the state of the container fragment when it pauses as follows:</p> <pre class="prettyprint"><code>@Override<br />public void onPause() {<br /> super.onPause();<br /> ((NestedFragApp) getActivity().getApplication()).setFragmentSavedState(<br /> SAVED_STATE_KEY, getFragmentManager().saveFragmentInstanceState(this));<br />}<br /></code></pre> <h4 id="initializing-the-fragment-transaction">Initializing the fragment transaction</h4> <p>Finally, remember to check whether there is a saved state for this fragment before “initializing” the fragment transaction:</p> <pre class="prettyprint"><code>SavedState fragmentSavedState = ((NestedFragApp)getActivity().getApplication())<br /> .getFragmentSavedState(SAVED_STATE_KEY);<br />if(fragmentSavedState == null){<br /> if (savedInstanceState == null) {<br /> getChildFragmentManager().beginTransaction().replace(R.id.nested_fragment_container, <br /> NestedFragmentOne.newInstance()).commit();<br /> } else {<br /> // use savedInstanceState here to restore state saved in onSaveInstance<br /> }<br />}<br /></code></pre> <p>Note that there are two “saved states” here:</p> <ol><li>The instance state saved in <code>onSaveInstanceState</code>, which is provided to you by the system via <code>savedInstanceState</code>.</li><li>The state you explicitly saved in <code>onPause</code>, which you retrieve from the <code>Application</code> object as <code>fragmentSavedState</code>.</li></ol> <p>The flow you follow for initializing the fragment is as follows:</p> <ul><li>You first check to see if you had previously explicitly saved state. If true, then you don’t need to do anything.</li><li>If not, then you proceed to check if the system had saved state for you. If true, then you use the <code>savedInstanceState</code> to restore system-saved state.</li><li>Only if neither is true, then you initiate the fragment transaction.</li></ul> <h4 id="letting-go-of-the-saved-state">Letting go of the saved state</h4> <p>One thing you need to be careful of is to not hold on to the saved fragment state any longer than necessary. For example, when the <strong>container <code>Fragment</code></strong> is destroyed, you want to invalidate the back-stack associated with it as well. This sounds obvious but I overlooked it and ended up with strange behaviors.</p> <p>The best way I found was to “forget” the saved state of a container fragment in its <code>onDestroy</code>:</p> <pre class="prettyprint"><code>@Override<br />public void onDestroy() {<br /> super.onDestroy();<br /> ((NestedFragApp) getActivity().getApplication()).setFragmentSavedState(<br /> SAVED_STATE_KEY, null);<br />}<br /></code></pre> <p>With all these steps in place, the app now behaves as one would expect it to. Your position within a back-stack, even within a nested fragment, is remembered even when you navigate away and return to the top level fragment.</p> <p>Here’s a video showing how the app now behaves:</p> <iframe src="//www.youtube.com/embed/7RpzkXGJqNo" allowfullscreen="" frameborder="0" height="315" width="420"></iframe> <p>The source code for the entire series is at <a href="https://github.com/curioustechizen/blog-nested-fragments-backstack">github</a>.</p><div class="se-section-delimiter"></div> <h3 id="conclusion">Conclusion</h3> <ul><li>Consider pro-actively saving your <code>Fragment</code> states in <code>onPause</code>, particularly is the <code>Fragment</code> happens to nest other fragments inside of it. </li><li>Do not rely solely on the system saving state for you in <code>onSaveInstanceState</code>.</li><li>Use <code>FragmentManager#saveFragmentInstanceState</code> to save the Fragment state including the back-stack of nested fragment transactions for you.</li><li>Do not hold on to the saved state any longer than necessary.</li></ul> <p>This article looked at ActionBar tabs with a ViewPager, but this concept applies to other situations where one would use nested Fragments (Navigation Drawers for example).</p></description>
<pubDate>Sun, 02 Feb 2014 15:05:00 +0530</pubDate>
<link>/blog/2014/02/02/nested-fragment-and-backstack-part-2/</link>
<guid isPermaLink="true">/blog/2014/02/02/nested-fragment-and-backstack-part-2/</guid>
<category>nested</category>
<category>fragments</category>
<category>programming</category>
<category>backstack</category>
<category>android</category>
</item>
<item>
<title>Nested Fragments and the Back Stack</title>
<description><p>This article is not about the back stack of <em>activities</em> that Android maintains for every task. That stuff has been written about adequately elsewhere. This post is about the back stack of <em>fragment transactions</em> maintained by the <a href="http://developer.android.com/reference/android/support/v4/app/FragmentManager.html"><code>FragmentManager</code></a> and how they relate to nested fragments.</p> <p><strong>Edit: Other posts in this series at</strong></p><ol><li><a href="http://curioustechizen.blogspot.com/2014/02/nested-fragment-and-backstack-part-2.html">Part 2</a></li><li><a href="http://curioustechizen.blogspot.com/2014/02/nested-fragments-and-backstack-part-3.html">Part 3</a></li></ol> <p><strong>Heads-up:</strong> If you are using nested fragments, you need to use the support library, even if your app only targets API level 14 and above. This is because nested fragment support was <a href="http://developer.android.com/about/versions/android-4.2.html#NestedFragments">added in API 17</a>, and the feature was back-ported to the support library (revision 11 and later).</p> <h3 id="tldr">TL;DR</h3> <p>The gist of this post can be stated as follows:</p> <blockquote> <p>There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its <strong>state will not be saved until its owning activity actually needs to save its state</strong>.</p></blockquote> <p>This is from the <a href="http://developer.android.com/reference/android/support/v4/app/Fragment.html#onSaveInstanceState%28android.os.Bundle%29">docs</a> (emphasis mine). Overlooking this can lead to bugs especially when you use nested fragments since the back stack of a child fragment manager could be reset when you least expect it. Remember - if the state of a <code>Fragment</code> is not saved, then by definition, the back stack of fragment transactions managed by that fragment’s child <code>FragmentManager</code> is not saved either.</p> <h3 id="the-problem">The Problem</h3> <p>With the advent of fragments, more so nested fragments, the general advice one gets from the developer community is this:</p> <blockquote> <p>Fragmentize all the everythings!</p></blockquote> <p>And with good reason too. Consider the following:</p> <ul><li>If you use ActionBar tabs, the content of each tab is implemented as a <code>Fragment</code>.</li><li>Each “page” in a <code>ViewPager</code> is often implemented as a <code>Fragment</code>.</li><li>In navigation drawers, the “content” of each navigation item is expected to be a <code>Fragment</code>.</li></ul> <p>What this translates to is that what would once be implemented as an <code>Activity</code> now needs to be implemented as a <code>Fragment</code>. This also means that a <em>flow within that <code>Activity</code></em>, that might have been implemented using <code>Fragment</code>s, now needs to be implemented using <strong>nested <code>Fragment</code>s</strong>. Note that by “flow” I simply mean a sequence of screens to establish a particular task.</p> <p>Now here’s the thing with flows: If a user “goes away” from a flow and later returns to it, it is expected that the user continues from the screen where they left off. Translated into <code>Fragment</code> terminology, this means that if a user navigates away and returns to a flow that is implemented using <code>Fragment</code>s, its is expected that the user’s position in the backstack of fragment transactions is retained. However, this isn’t always the case.</p> <p>Here is a video demonstrating the problem:</p> <iframe src="//www.youtube.com/embed/3gRq3hG9tS4" allowfullscreen="" frameborder="0" height="315" width="420"></iframe> <p>The video shows an <code>Activity</code> with three tabs. It is a modified version of an <code>Activity</code> created using the “New Activity” wizard in ADT or Android Studio and specifying “Fixed Tabs + Swipe” navigation. The modification is as follows:</p> <ul><li>The content of the first tab has been modified to make it a “Container” <code>Fragment</code> that in turn contains two nested fragments.</li><li>When the container fragment is first created, it shows a nested fragment asking you to enter your name.</li><li>On entering the name and Clicking “Next”, you are presented with another nested fragment asking you to enter your GitHub username.</li><li>The other two tabs are just simple <code>Fragment</code>s - no nesting business there.</li></ul> <p>Now, notice what happens when I follow this sequence:</p> <ol><li>Enter name, press Next. Then, enter a github username.</li><li>Navigate to the tab titled “Section 2” and then back to “Section 1”.</li><li>Navigate to the tab titled “Section 3” and then back to “Section 1”.</li></ol> <p>Uh! In step 3 above, the back stack was nuked. But hey, it didn’t happen in Step 2. Why so?</p> <h3 id="explanation">Explanation</h3> <p>This example uses a <code>ViewPager</code>. By default, a <code>ViewPager</code> has an “off screen limit” of 1. This means that in addition to the page being displayed, one adjacent page in each direction is kept in memory. So, when you navigate to “Section 2”, everything in “Section 1” is still intact in memory.</p> <p>When you navigate to “Section 3”, the page corresponding to “Section 1” is torn down. More importantly, since at this point the <code>Activity</code> instance state is not being saved, the <code>Fragment</code> state isn’t saved either. This ties in with what we saw in the “TL;DR” section above. As a result, when you navigate back to “Section 1”, the nested fragment back stack is reset.</p> <h3 id="rotation-task-switching">Rotation? Task Switching?</h3> <p>Try following this sequence of steps:</p> <ol><li>Enter name, press Next. Then, enter a github username.</li><li>Rotate the device; or switch to another app and return back to this app</li></ol> <p>Now you’ll see that the back stack is retained. This is because when you rotate the device or switch to another task, the Activity saves its instance state. As a consequence the container fragment does too.</p> <h3 id="conclusion">Conclusion</h3> <p>Re-iterating what we started off this post with, <strong>keep in mind when you are using nested fragments that a <code>Fragment</code> is guaranteed to save state only when the containing <code>Activity</code> saves its instance state. At other times, the <code>Fragment</code> might simply be torn down</strong>.</p> <p>The code for a sample app illustrating the problem is available <a href="https://github.com/curioustechizen/blog-nested-fragments-backstack">at github</a>. The next part of this series will explore ways to overcome this problem.</p></description>
<pubDate>Sat, 25 Jan 2014 23:09:00 +0530</pubDate>
<link>/blog/2014/01/25/nested-fragments-and-back-stack/</link>
<guid isPermaLink="true">/blog/2014/01/25/nested-fragments-and-back-stack/</guid>
<category>nested</category>
<category>fragments</category>
<category>programming</category>
<category>backstack</category>
<category>android</category>
</item>
<item>
<title>Android ListViews: "Hybrid" Choice Behavior</title>
<description><p>The goal of this post is to use a <code>ListView</code> in a master/detail configuration where <em>both</em> of the following are possible:</p> <ol><li>Touch a single item to <strong>open</strong> it.</li><li>Long-tap multiple items to <strong>choose</strong> them and perform a common action on them.</li></ol> <p>Note that we wish both these to be possible simultaneously, i.e., even as one item is opened, we wish to allow multiple items (possibly including the item that is opened) to be chosen.</p> <p>This behavior (with some minor variations) is seen in apps like GMail, Google Play Store and the Google I/O 2013 app.</p> <p>The following screenshot shows what we want to achieve. It shows one opened item (Item 5) and two chosen items (Item 3 and Item 8)</p> <p><img src="https://lh5.googleusercontent.com/-HVUbT2xSCHE/UbNPf0kqtFI/AAAAAAAAAHk/cAFBmm4HglY/s512/target_ui.png" alt="This is what we want to achieve" title="target_ui.png"></p> <h3 id="a-note-on-the-terminology">A note on the terminology</h3> <p>Just to avoid confusion, let's sort of formalize the terminology related to the states an item in the list can be in.</p> <blockquote> <p>An item is <strong>opened</strong> when the user is viewing the details about that item. In other words, the details of that item are being displayed in the <code>DetailFragment</code>. In dual-pane mode, there needs to be some visual indication in the <code>ListView</code> to let the user know which one of the items is currently opened.</p> <p>When an item is <strong>chosen</strong>, the Contextual Action Bar appears and the user can perform some action on the item. When multiple items are chosen, only the contextual actions that apply to all of them are to be presented. There needs to be some visual indication in the <code>ListView</code> to let the user know which of the items are currently chosen. Needless to say, this indication needs to differ from the that used to indicate the opened item.</p></blockquote> <h3 id="implementation">Implementation</h3> <p>You might notice that one can achieve the opened behavior using <code>ListView</code>'s <code>CHOICE_MODE_SINGLE</code> and the chosen behavior using <code>CHOICE_MODE_MULTIPLE_MODAL</code>. However, it is while trying to combine them that things begin to get challenging, particularly in dual-pane mode. You get either one or the other, but never both. For example, if you use <code>CHOICE_MODE_MULTIPLE_MODAL</code>, then you lose the ability to visually indicate the currently opened item.</p> <p>The solution I ended up with was to not rely on the <code>CHOICE_MODE_MULTIPLE_MODAL</code>, but rather simulate it myself. The high level steps are as follows:</p> <ol><li>Create a custom <code>ListAdapter</code> that keeps track of the currently opened item and the currently chosen items</li><li>In the <code>getView()</code> (or equivalent) method of your custom <code>ListAdapter</code>, examine the item at the supplied <code>position</code>. If it is the currently opened item, set its visual properties to indicate this. Ditto if it is one of the chosen items.</li><li>Listen for clicks and long clicks on your <code>ListView</code> and update the adapter defined in step 1 accordingly- i.e., in your <code>OnItemClickListener</code> implementation, set the opened item and in <code>OnItemLongClickListener</code>, update the list of chosen items.</li><li><code>OnItemLongClickListener</code> is also where you need to start the action mode (<code>getListView().startActionMode()</code>) if it isn't started already.</li></ol> <h3 id="hybridchoiceadapter">HybridChoiceAdapter</h3> <p>Here are relevant portions of the code showing how the Adapter should be customized. This code is sparsely commented since I hope that it is self explanatory. Please look at the end of this post for the link to the complete github project.</p> <pre class="prettyprint prettyprinted" style=""><code><span class="pln"> </span><span class="com">/* Keep track of currently opened item and chosen items */</span><span class="pln"><br /> </span><span class="kwd">private</span><span class="pln"> </span><span class="typ">Set</span><span class="pun">&lt;</span><span class="typ">Integer</span><span class="pun">&gt;</span><span class="pln"> chosenItems </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">HashSet</span><span class="pun">&lt;</span><span class="typ">Integer</span><span class="pun">&gt;();</span><span class="pln"><br /> </span><span class="kwd">private</span><span class="pln"> </span><span class="kwd">int</span><span class="pln"> openedItem </span><span class="pun">=</span><span class="pln"> </span><span class="pun">-</span><span class="lit">1</span><span class="pun">;</span><span class="pln"><br /><br /> </span><span class="com">//...snip...</span><span class="pln"><br /><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> setItemChosen</span><span class="pun">(</span><span class="kwd">int</span><span class="pln"> position</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">boolean</span><span class="pln"> chosen</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(!</span><span class="pln">chosen </span><span class="pun">&amp;&amp;</span><span class="pln"> isItemChosen</span><span class="pun">(</span><span class="pln">position</span><span class="pun">))</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> chosenItems</span><span class="pun">.</span><span class="pln">remove</span><span class="pun">(</span><span class="pln">position</span><span class="pun">);</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">else</span><span class="pln"> </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="pln">chosen </span><span class="pun">&amp;&amp;</span><span class="pln"> </span><span class="pun">!</span><span class="pln">isItemChosen</span><span class="pun">(</span><span class="pln">position</span><span class="pun">))</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> chosenItems</span><span class="pun">.</span><span class="pln">add</span><span class="pun">(</span><span class="pln">position</span><span class="pun">);</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">boolean</span><span class="pln"> isItemChosen</span><span class="pun">(</span><span class="kwd">int</span><span class="pln"> position</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> </span><span class="kwd">return</span><span class="pln"> chosenItems</span><span class="pun">.</span><span class="pln">contains</span><span class="pun">(</span><span class="pln">position</span><span class="pun">);</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Set</span><span class="pun">&lt;</span><span class="typ">Integer</span><span class="pun">&gt;</span><span class="pln"> getChosenItems</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> </span><span class="kwd">return</span><span class="pln"> chosenItems</span><span class="pun">;</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> setOpenedItem</span><span class="pun">(</span><span class="kwd">int</span><span class="pln"> position</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">openedItem </span><span class="pun">=</span><span class="pln"> position</span><span class="pun">;</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">int</span><span class="pln"> getOpenedItem</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">openedItem</span><span class="pun">;</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">boolean</span><span class="pln"> isItemOpened</span><span class="pun">(</span><span class="kwd">int</span><span class="pln"> position</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">openedItem </span><span class="pun">==</span><span class="pln"> position</span><span class="pun">;</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> clearChoices</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> chosenItems</span><span class="pun">.</span><span class="pln">clear</span><span class="pun">();</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> toggleItem</span><span class="pun">(</span><span class="kwd">int</span><span class="pln"> position</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="pln">isItemChosen</span><span class="pun">(</span><span class="pln">position</span><span class="pun">))</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> chosenItems</span><span class="pun">.</span><span class="pln">remove</span><span class="pun">(</span><span class="pln">position</span><span class="pun">);</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">else</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> chosenItems</span><span class="pun">.</span><span class="pln">add</span><span class="pun">(</span><span class="pln">position</span><span class="pun">);</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">int</span><span class="pln"> getChosenItemsCount</span><span class="pun">(){</span><span class="pln"><br /> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">chosenItems</span><span class="pun">.</span><span class="pln">size</span><span class="pun">();</span><span class="pln"><br /> </span><span class="pun">}</span></code></pre> <h3 id="the-getview-method">The <code>getView()</code> method</h3> <p>At this point, we have set up the <code>Adapter</code> to keep track of the currently opened item and the chosen items too. We have also exposed methods to manipulate these values. Now, lets look at the code that updates the UI. It is rather simple - all we need to do is, set the background of the row view depending on the opened and chosen states of the current item. Note that an item can be both opened and chosen.</p> <pre class="prettyprint prettyprinted" style=""><code><span class="pln"> </span><span class="lit">@Override</span><span class="pln"><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">final</span><span class="pln"> </span><span class="typ">View</span><span class="pln"> getView</span><span class="pun">(</span><span class="kwd">final</span><span class="pln"> </span><span class="kwd">int</span><span class="pln"> position</span><span class="pun">,</span><span class="pln"> </span><span class="typ">View</span><span class="pln"> convertView</span><span class="pun">,</span><span class="pln"><br /> </span><span class="typ">ViewGroup</span><span class="pln"> parent</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> </span><span class="typ">View</span><span class="pln"> v </span><span class="pun">=</span><span class="pln"> convertView</span><span class="pun">;</span><span class="pln"><br /> </span><span class="com">/*Normal procedure to inflate the row layout and set its properties goes here*/</span><span class="pln"><br /><br /> v</span><span class="pun">.</span><span class="pln">setBackgroundResource</span><span class="pun">(</span><span class="lit">0</span><span class="pun">);</span><span class="pln"><br /> </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="pln">isItemOpened</span><span class="pun">(</span><span class="pln">position</span><span class="pun">))</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> setViewAsOpened</span><span class="pun">(</span><span class="pln">v</span><span class="pun">);</span><span class="pln"> </span><span class="com">//This method sets the appropriate background resource or drawable</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /><br /> </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="pln">isItemChosen</span><span class="pun">(</span><span class="pln">position</span><span class="pun">))</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> setViewAsChosen</span><span class="pun">(</span><span class="pln">v</span><span class="pun">);</span><span class="com">//This method sets the appropriate background resource or drawable</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /><br /> </span><span class="kwd">return</span><span class="pln"> v</span><span class="pun">;</span><span class="pln"><br /> </span><span class="pun">}</span></code></pre> <h3 id="listening-for-clicks-on-the-listview">Listening for clicks on the <code>ListView</code></h3> <p>In your <code>Activity</code> or <code>Fragment</code>, we listen for both clicks and long clicks and update the adapter accordingly. Again, only the relevant portions of the code are presented here - the full project is shared on github (linked at the end of this post). Here we use a <code>ListAdapter</code> that also implements <code>OnItemLongClickListener</code>.</p> <pre class="prettyprint prettyprinted" style=""><code><span class="pln"> </span><span class="lit">@Override</span><span class="pln"><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> onListItemClick</span><span class="pun">(</span><span class="typ">ListView</span><span class="pln"> listView</span><span class="pun">,</span><span class="pln"> </span><span class="typ">View</span><span class="pln"> view</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">int</span><span class="pln"> position</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">long</span><span class="pln"> id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /> </span><span class="kwd">super</span><span class="pun">.</span><span class="pln">onListItemClick</span><span class="pun">(</span><span class="pln">listView</span><span class="pun">,</span><span class="pln"> view</span><span class="pun">,</span><span class="pln"> position</span><span class="pun">,</span><span class="pln"> id</span><span class="pun">);</span><span class="pln"><br /><br /> </span><span class="com">//When an item is clicked, set it as the opened item</span><span class="pln"><br /> mAdapter</span><span class="pun">.</span><span class="pln">setOpenedItem</span><span class="pun">(</span><span class="pln">position</span><span class="pun">);</span><span class="pln"><br /><br /> </span><span class="com">//At this point, clear all choices</span><span class="pln"><br /> mAdapter</span><span class="pun">.</span><span class="pln">clearChoices</span><span class="pun">();</span><span class="pln"><br /> </span><span class="kwd">if</span><span class="pun">(</span><span class="pln">mActionMode </span><span class="pun">!=</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">){</span><span class="pln"><br /> mActionMode</span><span class="pun">.</span><span class="pln">finish</span><span class="pun">();</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /> mAdapter</span><span class="pun">.</span><span class="pln">notifyDataSetChanged</span><span class="pun">();</span><span class="pln"><br /><br /> </span><span class="com">// code to show the details fragment goes here</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /><br /> </span><span class="lit">@Override</span><span class="pln"><br /> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">boolean</span><span class="pln"> onItemLongClick</span><span class="pun">(</span><span class="typ">AdapterView</span><span class="pun">&lt;?&gt;</span><span class="pln"> parent</span><span class="pun">,</span><span class="pln"> </span><span class="typ">View</span><span class="pln"> view</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">int</span><span class="pln"> position</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">long</span><span class="pln"> id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"><br /><br /> </span><span class="com">//When an item is long clicked, toggle its chosen state</span><span class="pln"><br /> </span><span class="com">//Also update the CAB title to reflect the change in number of chosen items</span><span class="pln"><br /> mAdapter</span><span class="pun">.</span><span class="pln">toggleItem</span><span class="pun">(</span><span class="pln">position</span><span class="pun">);</span><span class="pln"><br /> updateActionMode</span><span class="pun">();</span><span class="pln"><br /> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">;</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /><br /> </span><span class="kwd">private</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> updateActionMode</span><span class="pun">(){</span><span class="pln"><br /> </span><span class="kwd">if</span><span class="pun">(</span><span class="pln">mActionMode </span><span class="pun">==</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">){</span><span class="pln"><br /> mActionMode </span><span class="pun">=</span><span class="pln"> getListView</span><span class="pun">().</span><span class="pln">startActionMode</span><span class="pun">(</span><span class="pln">actionModeCallback</span><span class="pun">);</span><span class="pln"><br /> </span><span class="pun">}</span><span class="pln"><br /><br /> mActionMode</span><span class="pun">.</span><span class="pln">setTitle</span><span class="pun">(</span><span class="typ">String</span><span class="pun">.</span><span class="pln">format</span><span class="pun">(</span><span class="str">"%d chosen"</span><span class="pun">,</span><span class="pln"> mAdapter</span><span class="pun">.</span><span class="pln">getChosenItems</span><span class="pun">().</span><span class="pln">size</span><span class="pun">()));</span><span class="pln"><br /> mAdapter</span><span class="pun">.</span><span class="pln">notifyDataSetChanged</span><span class="pun">();</span><span class="pln"><br /> </span><span class="pun">}</span></code></pre> <p>The previous code snippet also includes step 4 from our high level overview. If the CAB is not already shown, we show it when an item is long clicked.</p> <p>That mostly covers what we need to do to achieve our goal. There are a few other things that need to be taken care of (for example, clearing the choices whenever the CAB is dismissed - as a result of a contextual action being performed, or otherwise). You can examine the entire code in detail at the github repository.</p> <h3 id="variations">Variations</h3> <p>There are subtle variations of what action the user has to take to choose an item. For example,</p> <ul><li>The old GMail app (v4.3) displayed check boxes for each row. So you could choose an item either by long-pressing it, or by tapping the check box.</li><li>In the new GMail app and the Google I/O 2013 app, when no item is chosen, you long-press an item to choose it. After that, <strong>even single clicking on other items chooses them</strong>. This is different from our implementation where a single-tap always opens an item.</li></ul> <p>You will need to modify the code for the click listeners if you want to go with one of these variations. The <code>ListAdapter</code> code itself should remain the same.</p> <h3 id="turning-this-into-a-library">Turning this into a library?</h3> <p>Well, I gave this a thought too. Exposing the custom <code>Adapter</code> as a library is the easy part. What I couldn't decide upon is how to include the <code>ListView</code> listeners in a library. Developers might wish to extend <code>ListActivity</code> or <code>ListFragment</code> or simply include a <code>ListView</code> in their layouts. Catering to so many requirements is a tough ask (unless I want to provide custom base versions of all these classes ... plus their <code>Sherlock</code> counterparts!)</p> <p>If anyone has any ideas on how this could be library-ized, please do drop a comment.</p> <h3 id="github-repositroy">GitHub repositroy</h3> <p>The complete source code for this article is available as a sample project on GitHub <a href="https://github.com/curioustechizen/android-hybridchoice">here</a>.</p></description>
<pubDate>Sat, 08 Jun 2013 23:33:00 +0530</pubDate>
<link>/blog/2013/06/08/android-listviews-hybrid-choice-behavior/</link>
<guid isPermaLink="true">/blog/2013/06/08/android-listviews-hybrid-choice-behavior/</guid>
<category>choicemode</category>
<category>listview</category>
<category>android</category>
</item>
<item>
<title>Shift to Octopress Postponed</title>
<description><div dir="ltr" style="text-align: left;" trbidi="on"><p>For some time now, I have been toying with the idea of migrating this blog to <a href="http://octopress.org/">octopress</a>. I'm already using Markdown to compose my posts, so this is a logical step for me. Also, the idea of a static site that I can take with me wherever I choose to host it appeals to me. Finally, there's the geek factor what with git-based publish workflows and SCSS/liquid customizations and what not. I had even chosen a theme - <a href="http://panks.me/blog/2013/01/new-octopress-theme-fabric/">Fabric</a> - to use as my base theme.</p><p>However, it looks like I'm going to have to postpone migration to Octopress. Here are some of the reasons:</p><h3>Redirection</h3><p>I'm not sure how to deal with links to my existing posts. I have seen examples of how to do this if you are self-hosting your current blog, or if you are using your own domain name. Neither of these apply to me - my current blog is hosted on blogger, with a <code>.blogspot</code> domain. </p><h3>Comments</h3><p>I'm already using Disqus for comments on my blog. I gather that it should be possible to migrate Disqus comments even if your domain changes. I just haven't figured out how.</p><h3>Importing</h3><p>I tried using some custom Ruby scripts to import my existing posts into Octopress. While it works, there are two problems I need to deal with:</p><ul><li><p><strong>Syntax Highlighting:</strong> In blogger, syntax highlighting is done dynamically by Javascript (I use google's prettify.js). While this can be used with static site generators, it is best to stick to introducing syntax highlighting at the <em>post generation time</em>. This is all fine for new posts, but for posts that I import from blogger, this needs additional tweaking. Basically the imported sources are just HTML with some YAML front-matter. I will need to convert it to markdown, add the syntax highlighting annotations and then generate the posts from it.</p></li><li><p><strong>Permalinks:</strong> This goes back to the redirection I already mentioned. I also need to customize the permalinks of imported posts to make sure they play nice with redirection. Again, this is not a problem for newer posts. Only the imported posts need to be tweaked.</p></li></ul><h3>Looking Forward</h3><p>I'm not saying that any of the above impossible (or even very difficult) to achieve. It is just that some amount of experimentation is involved. I feel that it would take up more time than I am willing to invest at this point to get things up and running.</p><p>This is not to say that I have shelved the idea of shifting to a static site generator altogether. On the contrary. This shift is surely happening. It has just been deferred.</p><p>The easiest approach would be to maintain my current blog at http://curioustechizen.blogspot.com/ and start the octopress blog afresh. No imports from blogger. No redirection. Only new posts at the new blog. This approach is not without its downsides though.</p><p>So, in a nutshell:</p><blockquote><p>I will surely be migrating to a static site generator like octopress in the near future. But for now, I'm sticking with blogger.</p></blockquote><br /></div></description>
<pubDate>Sat, 09 Mar 2013 11:04:00 +0530</pubDate>
<link>/blog/2013/03/09/shift-to-octopress-postponed/</link>
<guid isPermaLink="true">/blog/2013/03/09/shift-to-octopress-postponed/</guid>
<category>migration</category>
<category>platform</category>
<category>octopress</category>
<category>publishing</category>
</item>
<item>
<title>Android Constants: Preference Keys, Actions, Extras and more</title>
<description><p>The content of this post may seem ... well .. trivial at first, but I have tripped over these so many times that I decided to write it up - at least to keep me reminded of it, if not for any other reason!</p><p>If you have written anything more than a HelloWorld app in Android, chances are you have had to work with a plethora of program elements that are represented as <code>String</code>s. Consider this sampling:</p><ul><li>Keys for <code>SharedPreferences</code> are <code>String</code>s</li><li>Keys for <code>Bundle</code>s are <code>String</code>s</li><li><code>Intent</code> extras are <code>Bundle</code>s, and hence, if you want to include any extras or retrieve them from <code>Intent</code>s, you use their <code>String</code> keys to work with them. Ditto with <code>Fragment</code> arguments</li><li><code>Intent</code> and <code>IntentFilter</code> actions (and categories) are <code>String</code>s themselves</li><li>. . .</li></ul><p>I used to deal with these the lazy way: Declare the keys as <code>public static</code> where they are first used (or where they "belong" logically) and refer to them from wherever they are needed in the code. Examples of the class that is the logical owner might be:</p><ul><li>The class that broadcasts an <code>Intent</code></li><li>The class that creates or sends a non-broadcast <code>Intent</code> (this might be an <code>Activity</code> or <code>Service</code> for example)</li><li>The class that creates a <code>SharedPreference</code> for editing</li></ul><p>However, I quickly found out that often it is not possible to cleanly define these keys as belonging to a particular class. Further, since you might end up with a handful of extras, qualifying the class name becomes tedious - more so since it is likely that Activities or Services can have quite long names. How readable is this snippet?</p><p><a id="basic-example"></a></p><pre class="prettyprint"><code>if(AbstractBaseLiveModeActivity.ACTION_LIVE_UPDATE.equals(intent.getAction())){<br /> Bundle extras = intent.getExtras();<br /> if(extras.containsKey(AbstractBaseLiveModeActivity.EXTRA_LIVE_UPDATE_TIMESTAMP)){<br /> long timestamp = extras.getLong(AbstractBaseLiveModeActivity.EXTRA_LIVE_UPDATE_TIMESTAMP);<br /> // Do something with timestamp here<br /> }<br />}<br /></code></pre><h3>Constants Almighty</h3><p>One common solution to this problem is to put everything into one "God" object called <code>Constants</code> or whatever, and prefix the constant names with <code>EXTRA_</code>, <code>ACTION_</code> or other such descriptive characters to keep them distinct.</p><pre class="prettyprint"><code>public class Constants{<br /> private Constants(){}<br /><br /> public static final String ACTION_LIVE_UPDATE = "com.myawesomeapp.action.LIVE_UPDATE";<br /> // ...<br /><br /> public static final String EXTRA_LIVE_UPDATE_TIMESTAMP = "com.myawesomeapp.extra.LIVE_UPDATE_TIMESTAMP";<br /> // ...<br /><br />}<br /></code></pre><p>Now, we've solved the readability problem since we just qualify the constant names with <code>Constant.</code> So, all's well, right?</p><p><a id="disadvantages"></a><strong>Wrong!</strong></p><p>The problem with this approach is as the number of extras, actions and preference keys increases, the <code>Constants</code> class quickly becomes unmanageable. Also, having to use the <code>ACTION_</code> and <code>EXTRA_</code> prefixes hinders usability with some IDE's. For example, with Eclipse, even if you know that you want <code>EXTRA_LIVE_UPDATE_TIMESTAMP</code>, you are forced to type the first six characters without which the code assist will not be able to filter only the extras.</p><p>Try using Eclipse to find a particular action or extra from the <code>Intent</code> class if you want to see a real-world example of what I mean.<br></p><p><a id="split-constant-files"></a></p><h3>Split it up into distinct constant files</h3><p>Here's what I do to keep my code free of such stutter. I simply split up the "God" <code>Constants</code> class into several smaller, easier-to-manage constants classes. Like so:</p><pre class="prettyprint"><code>public class Extras{<br /> private Extras(){}<br /><br /> private static String createExtra(String suffix){<br /> return Constants.NAMESPACE_PREFIX + ".extra."+suffix; //NAMESPACE_PREFIX could be "com.myawesomeapp"<br /> }<br /><br /> public static final String LIVE_UPDATE_TIMESTAMP = createExtra("LIVE_UPDATE_TIMESTAMP");<br /> public static final String LIVE_UPDATE_VALUE = createExtra("LIVE_UPDATE_VALUE");<br /> public static final String FRIEND_ID = createExtra("FRIEND_ID");<br /> // ...<br /><br />}<br /><br />public class Broadcasts{<br /> private Broadcasts(){}<br /><br /> private static String createBroadcast(String suffix){<br /> return Constants.NAMESPACE_PREFIX + ".broadcast."+suffix; //NAMESPACE_PREFIX could be "com.myawesomeapp"<br /> }<br /><br /> public static final String LIVE_UPDATE = createBroadcast("LIVE_UPDATE");<br /> public static final String FRIEND_OFFLINE = createBroadcast("FRIEND_OFFLINE");<br /> // ...<br />}<br /><br />public class Actions{<br /> private Actions(){}<br /><br /> private static String createAction(String suffix){<br /> return Constants.NAMESPACE_PREFIX + ".action."+suffix; //NAMESPACE_PREFIX could be "com.myawesomeapp"<br /> }<br /><br /> public static final String JOIN_CHAT = createAction("JOIN_CHAT");<br /> // ...<br />}<br /></code></pre><p>You could create classes for Categories, Preference Keys and so on. Note that I differentiate between Broadcasts and Actions because although they are both Intents, they are logically very different. Now, <a href="#basic-example">this code snippet</a> changes to:</p><pre class="prettyprint"><code>if(Broadcasts.LIVE_UPDATE.equals(intent.getAction())){<br /> Bundle extras = intent.getExtras();<br /> if(extras.containsKey(Extras.LIVE_UPDATE_TIMESTAMP)){<br /> long timestamp = extras.getLong(Extras.LIVE_UPDATE_TIMESTAMP);<br /> // Do something with timestamp here<br /> }<br />}<br /></code></pre><p>Which code snippet would your rather see, especially six months from now when you have to fix a bug? Also note that we've made it far more easy to find the exact action or extra that we want using our IDEs.<br></p><h3>Wait, what about constants in XMLs?</h3><p>Glad you asked. In android, many of these constants are used not only in Java code, but also from XML files.</p><ul><li>Preference keys can be referenced in <a href="http://developer.android.com/guide/topics/ui/settings.html#DefiningPrefs">preferences XML</a> files via the <code>&lt;PreferenceScreen&gt;</code> element.</li><li>Intents can be declared in <code>AndroidManifest.xml</code>. This means, the <code>Intent</code> action and categories can be referenced from the manifest.</li><li><code>BroadcastReceiver</code>s can be declared in <code>AndroidManifest.xml</code>. The <code>&lt;intent-filter&gt;</code> action and categories are referenced here.</li><li>. . .</li></ul><p>This presents a problem since we end up duplicating the constants here. We cannot use our <code>Broadcasts.LIVE_UPDATE</code> constant in XML, so we tend to repeat the constant value:</p><pre class="prettyprint"><code>&lt;intent-filter&gt;<br /> &lt;action android:name="com.myawesomeapp.broadcast.LIVE_UPDATE"/&gt;<br />&lt;/intent-filter&gt;<br /></code></pre><p>This is not good. Any change to any constant involves updating it at multiple places. What's more, these issues are not caught at compile time and can be hard to debug.<br></p><h3>Using String resources to avoid duplication</h3><p>One way to avoid constant literal duplication issue explained in the previous section is to use <a href="http://developer.android.com/guide/topics/resources/string-resource.html">string resources</a>. You are already using string resources for a variety of strings in your Android app. (Wait, you aren't? I strongly suggest you start doing so right now). All you need to do is add the constants as additional string resources. </p><p>To keep things clean, you could keep these constants in their own file under <code>values/</code> folder - for example <code>constants.xml</code>. In there, you could add</p><pre class="prettyprint"><code>&lt;resources&gt;<br /><br /> &lt;!-- Broadcast Actions --&gt;<br /> &lt;string name="broadcast_live_update"&gt;com.myawesomeapp.broadcast.LIVE_UPDATE&lt;/string&gt;<br /> &lt;string name="broadcast_friend_offline"&gt;com.myawesomeapp.broadcast.FRIEND_OFFLINE&lt;/string&gt;<br /><br /> &lt;!-- Intent Extras --&gt;<br /> &lt;string name="extra_live_update_timestamp"&gt;com.myawesomeapp.extra.LIVE_UPDATE_TIMESTAMP&lt;/string&gt;<br /> &lt;string name="extra_live_update_value"&gt;com.myawesomeapp.extra.LIVE_UPDATE_VALUE&lt;/string&gt;<br /> &lt;string name="extra_friend_id"&gt;com.myawesomeapp.extra.FRIEND_ID&lt;/string&gt;<br /><br /> &lt;!-- Preference Keys --&gt;<br /> &lt;string name="pref_key_update_interval"&gt;UPDATE_INTERVAL&lt;/string&gt;<br /> &lt;string name="pref_key_theme"&gt;THEME&lt;/string&gt;<br /><br />&lt;/resources&gt;<br /></code></pre><p>Then, you could access these values from XML as follows:</p><pre class="prettyprint"><code>&lt;intent-filter&gt;<br /> &lt;action android:name="@string/broadcast_live_update"/&gt;<br />&lt;/intent-filter&gt;<br /><br />&lt;Preference <br /> android:key="@string/pref_key_update_interval"<br /> ... /&gt;<br /></code></pre><p>And so on. In Java code, you'd access these as:</p><pre class="prettyprint"><code>if(getString(R.string.broadcast_live_update).equals(intent.getAction())){<br /> // ...<br />}<br /><br />mSharedPref.getLong(getString(R.string.pref_key_update_interval));<br /></code></pre><p><strong>Unfortunately, this solution has all the disadvantages I mentioned in an <a href="#disadvantages">earlier section</a></strong>. </p><p>Your <code>constants.xml</code> will quickly become a monolithic clutter. This can be addressed by creating a separate XML file for each type of constant - like <code>broadcasts.xml</code>, <code>pref_keys.xml</code> etc. Even if you do that, you will still be accessing all the resources using <code>@string/blah</code> and <code>R.string.blah</code>.</p><p>Also, IDE content assist is still a problem. Your resource names will need to be prefixed with <code>action_</code> or <code>broadcast_</code> or <code>pref_key_</code> etc and finding the key you need could be frustrating.<br></p><h3>A workable strategy</h3><p>Here's a strategy I follow to decide how I should declare these constants:</p><ul><li>For preference keys, prefer string resources. This is because you are most likely to be building your Settings screens with XML anyway.</li><li>For all other key constants, prefer <a href="#split-constant-files">split constant files</a>.</li><li>Only if you need to use these from XML, declare them as string resources.</li></ul></description>
<pubDate>Mon, 18 Feb 2013 13:30:00 +0530</pubDate>
<link>/blog/2013/02/18/android-constants-preference-keys/</link>
<guid isPermaLink="true">/blog/2013/02/18/android-constants-preference-keys/</guid>
<category>technique</category>
<category>programming</category>
<category>constants</category>
<category>android</category>
</item>
<item>
<title>Android: Passing an arbitrary object to a custom View</title>
<description><p>So, I came across a situation where I wanted to create a custom <code>View</code> in Android (let's call it <code>MyAwesomeView</code>). I had to work with a couple of constraints:</p><ol><li>I have to be able to pass in an additional object to <code>MyAwesomeView</code>.</li><li>The <code>MyAwesomeView</code> should also be usable from XML.</li><li>The <code>MyAwesomeView</code> should be distinct from the application itself - i.e., it should be possible to distribute the <code>MyAwesomeView</code> as a library.</li></ol><p>To elaborate a bit on the "pass in an additional object" part: <code>View</code> provides three standard constructors using which you can pass in </p><ul><li>a <code>Context</code>, </li><li>an <code>AttributeSet</code> and </li><li>an <code>int</code> representing the style.</li></ul><p>I want to also pass in a <a href="https://github.com/chrisbanes/Android-BitmapCache"><code>BitmapCache</code></a> object since <code>MyAwesomeView</code> uses lots of <code>Bitmap</code>s and I don't want to encounter the dreaded <code>OutOfMemoryError</code> that goes hand in hand with decoding large bitmaps in an Android app. <code>MyAwesomeView</code> decodes a bitmap only if it is not already present in the cache.</p><p>The second constraint makes things really difficult. It is possible to pass in additional "configuration" information to a <code>View</code> by <a href="http://developer.android.com/training/custom-views/create-view.html#customattr">creating custom attributes</a>. However, this obviously cannot be used to pass in an object like a <code>BitmapCache</code>.</p><h3>Augmenting the <code>Context</code> object with additional information</h3><p>This solution I came across is as follows:</p><ul><li>Define an interface <code>BitmapCacheProvider</code> with a single method <code>provideBitmapCache()</code>;</li><li>Make your <code>Activity</code> class implement the interface defined in step 1. Override the interface method to return an appropriate <code>BitmapCache</code> object.</li><li>In the constructor of <code>MyAwesomeView</code>, check to see if the context object passed in to implements the <code>BitmapCacheProvider</code> interface. If it does - we're good. If not, then fail fast (or disable cacheing - whatever works for you).</li></ul><p>In code, here's what this would look like:</p><pre class="prettyprint"><code>/**<br /> * Interface to be implemented by the Context (Activity etc) in which `MyAwesomeView` runs<br /> */<br />public interface BitmapCacheProvider{<br /> BitmapCache provideBitmapCache();<br />}<br /><br />/**<br /> * An example of an Activity that implements BitmapCacheProvider<br /> */<br /><br />public class MyActivity extends Activity implements BitmapCacheProvider{<br /> //... Life-cycle methods of the Activity here<br /><br /> @Override<br /> public BitmapCache provideBitmapCache(){<br /> //Get your instance of bitmapcache here - probably from your Application<br /> BitmapCache bitmapCache = ...;<br /> return bitmapCache;<br /> }<br />}<br /><br />/**<br /> * Custom View that uses an additional object (BitmapCache) for its configuration.<br /> */<br />public class MyAwesomeView extends View{<br /> private BitmapCache mBitmapCache;<br /><br /> public MyAwesomeView(Context context){<br /> init(context, null, 0);<br /> }<br /><br /> public MyAwesomeView(Context context, AttributeSet attrs){<br /> init(context, attrs, 0);<br /> }<br /><br /> public MyAwesomeView(Context context, AttributeSet attrs, int style){<br /> init(context, attrs, style);<br /> }<br /><br /> private void init(Context context, AttributeSet attrs, int style){<br /> try{<br /> /*<br /> * Try casting the contex to BitmapCacheProvider. <br /> * <br /> * If the required interface is not implemented, <br /> * it'll throw a ClassCastException<br /> */<br /> mBitmapCache = ((BitmapCacheProvider) context).provideBitmapCache();<br /> } catch(ClassCastException e){<br /> throw new ClassCastException(context.toString()<br /> + " must implement BitmapCacheProvider");<br /> }<br /><br /> //At this point, we have the BitmapCacheObject which we can use for further processing.<br /> }<br /><br />}<br /></code></pre><h3>Conclusion:</h3><p>What we saw in this post was how it is possible to create a custom <code>View</code> in Android, that can take in an arbitrary object in its constructor - and still be usable from XML. Admittedly, it is a bit round-about, but it has its benefits. Here are a few other points worth considering if you are following this approach:</p><ul><li>In this example, I just augmented the main <code>Activity</code> with the desired <code>interface</code>, but you might need to do this for other classes. Basically, the <code>Context</code> that is passed in to the custom <code>View</code> constructor must be enhanced to implement the interface. What this context is depends on how you are including the custom <code>View</code>.</li><li>You might argue that the BitmapCache should be part of the custom <code>View</code> and not passed in to it by the application. This depends on the use case. If you have multiple custom Views that require Bitmap cacheing (as is the case with my app), it probably makes sense for the app to maintain the cache. We might not want too maintain too many caches lest the cache overhead cancels out any benefits we derive from having the cache in the first place!</li></ul></description>
<pubDate>Fri, 01 Feb 2013 09:34:00 +0530</pubDate>
<link>/blog/2013/02/01/android-passing-arbitrary-object-to/</link>
<guid isPermaLink="true">/blog/2013/02/01/android-passing-arbitrary-object-to/</guid>
<category>custom-view</category>
<category>android</category>
</item>
<item>
<title>Android: is onDestroy the new onStop?</title>
<description><p>Conventional Android development logic dictates that if there is some action you want to perform (or rather, stop performing) when your <code>Activity</code> is no longer visible to the user, do it in <code>onStop()</code>. Likewise, if there is some action you want to restart performing when the user restarts interacting with your <code>Activity</code>, do it in <code>onStart()</code>. The disadvantage of this approach, of course, is that it wouldn't play well with device orientation changes. </p><p>This post explores a couple of solutions to this problem, and concludes that there are cases where one has no choice but to postpone the actions that would be ideally taken in <code>onStop()</code>, to <code>onDestroy()</code>.</p><h3>A trivial (incorrect) example</h3><pre class="prettyprint"><code>public TrivialIncorrectActivity extends Activity{<br /><br /> //onCreate() and other life-cycle overrides like onResume() go here ...<br /><br /> @Override public void onStart(){<br /> super.onStart();<br /> startMakingThatPeriodicRestCall();<br /> }<br /><br /> @Override public void onStop(){<br /> super.onStop();<br /> stopMakingThatPeriodicRestCall();<br /> }<br /><br /> // ... Other life-cycle overrides like onDestroy() go here<br /><br />}<br /></code></pre><p>This example is incorrect. Every time the user rotates the device, your app would stop making a REST call and then again start making the call. Not good at all.</p><h3><code>setRetainInstance</code> to the rescue . . .</h3><p>API 11 introduced the Fragment API, and along with it, the <a href="http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)">setRetainInstance</a> method, which is also usable with older versions of Android by means of the <a href="http://developer.android.com/tools/extras/support-library.html">support library</a>. You can go through the documentation to understand the effect of a <code>setRetainInstance(true)</code>. Essentially, when a configuration change is happening, even though the hosting <code>Activity</code> is being re-created, the <code>Fragment</code> instance is not destroyed.</p><p>So, this allows us to improve upon our previous example. </p><pre class="prettyprint"><code>public IncorrectRotationTolerantActivity extends FragmentActivity{<br /><br /> private static final String TAG_RETAIN_FRAGMENT = "RetainFragment";<br /><br /> @Override<br /> protected void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> if(savedInstanceState == null){<br /> getSupportFragmentManager().beginTransaction()<br /> .add(IncorrectRetainFragment.newInstance(), TAG_RETAIN_FRAGMENT).commit();<br /> }<br /> }<br />}<br /><br />public class IncorrectRetainFragment extends Fragment{<br /><br /> public IncorrectRetainFragment(){}<br /><br /> public static IncorrectRetainFragment newInstance(){<br /> IncorrectRetainFragment frag = new IncorrectRetainFragment();<br /> frag.setRetainInstance(true);<br /> return frag;<br /> }<br /><br /> @Override<br /> public void onStart() {<br /> super.onStart();<br /> startMakingThatPeriodicRestCall();<br /> }<br /><br /> @Override<br /> public void onStop() {<br /> super.onStop();<br /> stopMakingThatPeriodicRestCall();<br /> }<br /><br />}<br /></code></pre><p>This code snippet still doesn't do what we want it to do. It does <strong>not</strong> prevent re-making that REST call during orientation changes. Why?</p><p>Because, <code>setRetainInstance</code> doesn't prevent a Fragment's <code>onStop()</code> from being called - it just prevents <code>onDestroy()</code> from being called. So, even if you ask for a Fragment instance to be retained across configuration changes, the <code>onStop()</code> method of the Fragment is always still called when the device is rotated.</p><h3><code>onDestroy()</code> is the new <code>onStop()</code></h3><p>To fix the problem, postpone stopping the REST call to the <code>onDestroy()</code> of the Fragment. Similarly, start making the call in <code>onCreate()</code> instead of in <code>onStart()</code>, since <code>onCreate()</code> is not called when the device is rotated, but <code>onStart()</code> is.</p><pre class="prettyprint"><code>public RotationTolerantActivity extends FragmentActivity{<br /><br /> private static final String TAG_RETAIN_FRAGMENT = "RetainFragment";<br /><br /> @Override<br /> protected void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> if(savedInstanceState == null){<br /> getSupportFragmentManager().beginTransaction()<br /> .add(RetainFragment.newInstance(), TAG_RETAIN_FRAGMENT).commit();<br /> }<br /> }<br />}<br /><br />public class RetainFragment extends Fragment{<br /><br /> public RetainFragment(){}<br /><br /> public static RetainFragment newInstance(){<br /> RetainFragment frag = new RetainFragment();<br /> frag.setRetainInstance(true);<br /> return frag;<br /> }<br /><br /> @Override<br /> public void onCreate(Bundle savedInstanceState) {<br /> super.onStart(savedInstanceState);<br /> startMakingThatPeriodicRestCall();<br /> }<br /><br /> @Override<br /> public void onDestroy() {<br /> super.onStop();<br /> stopMakingThatPeriodicRestCall();<br /> }<br /><br />}<br /></code></pre><p>This seems so semantically wrong though. <code>onDestroy()</code> represents the end of the <em>entire lifetime</em> of an Activity/Fragment and what we really wanted to do was monitor the <em>visible lifetime</em>. Also, there is no guarantee that <code>onDestroy()</code> will ever be called. If you really try out this example on a phone or emulator, chances are that you'll never see the Rest call being stopped - at least not right away.</p><h3>A more correct, more restrictive solution:</h3><p>There exists another solution to this problem - but it works only on API 11 and later, because it uses methods introduced in API 11 - <code>isChangingConfigurations()</code> and <code>getChangingConfigurations()</code>.</p><pre class="prettyprint"><code>public RotationTolerantActivity extends FragmentActivity{<br /><br /> private boolean mRotated;<br /><br /> @Override<br /> protected void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> Boolean nonConfigState =<br /> (Boolean)getLastCustomNonConfigurationInstance();<br /> if (nonConfigState == null) {<br /> mRotated = false;<br /> } else {<br /> mRotated = nonConfigState.booleanValue();<br /> }<br /> }<br /><br /> @Override <br /> public void onStart(){<br /> super.onStart();<br /> if(!mRotated){<br /> startMakingThatPeriodicRestCall();<br /> }<br /> }<br /><br /> @Override<br /> public void onStop(){<br /> super.onStop();<br /> mRotated = false;<br /> if (isChangingConfigurations()) {<br /> int changingConfig = getChangingConfigurations();<br /> if ((changingConfig &amp; ActivityInfo.CONFIG_ORIENTATION) == ActivityInfo.CONFIG_ORIENTATION) {<br /> mRotated = true;<br /> }<br /> }<br /><br /> if(!mRotated){<br /> stopMakingThatPeriodicRestCall();<br /> }<br /> }<br /><br /> @Override<br /> public Object onRetainCustomNonConfigurationInstance() {<br /> return mRotated ? Boolean.TRUE : Boolean.FALSE;<br /> }<br /><br />}<br /></code></pre><p>This solution is semantically correct, and works as expected. However, <strong>it only works on API 11 and higher, <em>even though we extend <code>FragmentActivity</code> from the support library</em> </strong>.</p><h3>Bonus: Why <code>onStop()</code> and not <code>onPause()</code>?</h3><p>The keen reader would have observed that this post talks about stopping un-needed tasks in <code>onStop()</code>and not <code>onPause()</code> - even though <code>onPause()</code> is the only one of these methods that is guaranteed to be called. Remember that after <code>onPause()</code> is called, the process could be killed in order to reclaim memory and thus <code>onStop()</code> and <code>onDestroy()</code> might never be called.</p><p>Yet, this entire post insists on using <code>onStop()</code> to stop un-needed tasks. The reason for this lies in the technique used in my library <a href="https://github.com/curioustechizen/android-app-pause">android-app-pause</a>. Unfortunately, this library in its current form does not handle device orientation changes correctly. This will be fixed in a future release though.</p></description>
<pubDate>Tue, 29 Jan 2013 10:00:00 +0530</pubDate>
<link>/blog/2013/01/29/android-ondestroy-is-new-onstop/</link>
<guid isPermaLink="true">/blog/2013/01/29/android-ondestroy-is-new-onstop/</guid>
<category>orientation</category>
<category>life-cycle</category>
<category>programming</category>
<category>onStop</category>
<category>android</category>
<category>onDestroy</category>
</item>
<item>
<title>Extensibility and Immutability in Java</title>
<description><h3>Objective:</h3><blockquote><p><strong>To devise a way to make thread-safe, a Java class designed to be extensible.</strong></p></blockquote><h3>Introduction:</h3><p><em>Effective Java, Second Edition: Item 15</em> says <strong>"Minimize Mutability"</strong>. One should always try to make a class immutable. This has several advantages that I will not go over here (Since <em>Effective Java</em> explains it all). I will however point out one of those advantages since it is central to this discussion: </p><blockquote><p><strong>Making a class immutable is the easiest way to ensure that the class is thread-safe.</strong></p></blockquote><p>There is however a problem: to make a class <em>truly immutable</em>, you must prevent it from being sub-classed. Either the class must be declared <code>final</code>, or it should have a <code>private</code> constructor and provide <code>static</code> factory methods instead of constructors. The reasons for this are outlined in <em>Effective Java</em>. The basic premise is that a sub-class can violate the immutability guarantees. </p><p>This must-not-be-subclassed restriction may be fine if you are applying immutability to some <em>value object</em> like <code>User</code>, <code>Point</code>, <code>Account</code> etc. However, the same requirement turns out to be overly restrictive if you are applying the concept to <em>logic classes</em>. This is because logic classes are often meant to be customized by extension. </p><h3>A strongly-immutable logic class:</h3><p>As an example of a logic class, consider the following ReportGenerator:</p><pre class="prettyprint"><code>public final class ReportGenerator{<br /> private final DatabaseLayer mDatabaseLayer;<br /> private final PresentationLayer mPresentationLayer;<br /><br /> public ReportGenerator(DatabaseLayer db, PresentationLayer pres){<br /> this.mDatabaseLayer = db;<br /> this.mPresentationLayer = pres;<br /> }<br /><br /> public void generateMonthlyReport(User user){<br /> Report report = mDatabaseLayer.getReport(user);<br /> mPresentationLayer.present(report);<br /> }<br />}<br /></code></pre><p>The other classes have been ommitted for brevity. Assume that <code>DatabaseLayer</code> and <code>PresentationLayer</code> classes are themselves immutable. This makes <code>ReportGenerator</code> <strong>strongly immutable</strong> and hence, thread-safe.</p><p>Now, suppose in the next phase of the project, you need to add a way to generate a historical report. The easiest way that comes to mind is to inherit from <code>ReportGenerator</code>. Unfortunately, we cannot do this since in order to make <code>ReportGenerator</code> immutable, we have declared it <code>final</code>. One possible approach to solving this issue is making <code>ReportGenerator</code> <strong>weakly immutable</strong>. This is discussed in the next section.</p><h3>A weakly-immutable logic class:</h3><p>One can relax the restriction that an immutable class must not be extensible, while still maintaining the guarantees, <strong>provided the sub-class adheres to the established contract</strong>. This is done by removing the <code>final</code> modifier from the class declaration, and making all fields <code>protected final</code>, or keep them <code>private final</code> and provide getters which we then use in the sub-classes. Both these approaches are shown in the code below.</p><pre class="prettyprint"><code>public class ReportGenerator{<br /> protected final DatabaseLayer mDatabaseLayer; //protected field approach<br /> private final PresentationLayer mPresentationLayer; //private field with accessor approach<br /><br /> public ReportGenerator(DatabaseLayer db, PresentationLayer pres){<br /> this.mDatabaseLayer = db;<br /> this.mPresentationLayer = pres;<br /> }<br /><br /> public PresentationLayer getPresentationLayer(){<br /> return this.mPresentationLayer;<br /> }<br /><br /> public void generateMonthlyReport(User user){<br /> Report report = mDatabaseLayer.getReport(user);<br /> mPresentationLayer.present(report);<br /> }<br />}<br /></code></pre><p>We can now sub-class this as follows:</p><pre class="prettyprint"><code>public class HistoricalReportGenerator extends ReportGenerator{<br /><br /> public HistoricalReportGenerator(DatabaseLayer db, PresentationLayer pres){<br /> super(db, pres);<br /> }<br /><br /> public void generateHistoricalReport(User user, Duration duration){<br /> Report historicalReport = mDatabaseLayer.getReport(user, duration);<br /> getPresentationLayer().present(historicalReport);<br /> }<br />}<br /></code></pre><p>We could also have added more <code>protected final</code> fields to the sub-class if needed. </p><p>What we now have is a weakly immutable class. <strong>This class is immutable as long as sub-classes adhere to the contract</strong>. It is a good idea to establish in the class javadoc, the expectation that sub-classes <strong>MUST</strong> preserve the same weak immutability restrictions that this class adheres to. If a sub-class willfully violates the contract, then the logic class cannot be depended upon to work correctly.</p><p>Here's an example to how to establish this contract:</p><pre class="prettyprint"><code>/**<br /> * The logic class that generates the report.<br /> * ... ...<br /> * &lt;br/&gt;&lt;br/&gt;<br /> * This class is &lt;em&gt;weakly immutable&lt;/em&gt;. It has been kept open for <br /> * extensibility. Sub-classes &lt;strong&gt;MUST&lt;/strong&gt; preserve the immutability <br /> * guarantees of this class. In particular, they must have only immutable <br /> * fields; and must not override any of the methods defined in this class to<br /> * return a mutable reference.<br /> *<br /> */<br /><br />public class ReportGenerator{<br /> //Class body omitted.<br />}<br /></code></pre><p>Since immutability is enforced by documentation rather than by the compiler, this is an acceptable compromise. It allows us to easily create thread-safe classes that are also extensible. This makes writing API's and frameworks that much easier.</p><h3>Thread-safety is more than Immutability:</h3><p>Of course, making a class immutable is not the only way to make a class thread-safe. A mutable class can be written such that it is thread-safe too. It is often desirable for an object to change its state during the execution of a program. How that is done is beyond the scope of this article. I suggest looking at <em>Java Concurrency In Practice</em> for details on this topic.</p><h3>Extending the logic class by Composition:</h3><p>There exists an alternative way to extend the functionality of <code>ReportGenerator</code> that does not involve inheriting from it: <strong>"Favor Composition over Inheritance"</strong> (<em>Effective Java, Second Edition, Item 16</em>). For completeness, I present the code for this approach here. Do note that this example uses the strongly immutable form of <code>ReportGenerator</code>.</p><pre class="prettyprint"><code>public final class ReportGenerator{<br /> private final DatabaseLayer mDatabaseLayer;<br /> private final PresentationLayer mPresentationLayer;<br /><br /> public ReportGenerator(DatabaseLayer db, PresentationLayer pres){<br /> this.mDatabaseLayer = db;<br /> this.mPresentationLayer = pres;<br /> }<br /><br /> public PresentationLayer getPresentationLayer(){<br /> return this.mPresentationLayer;<br /> }<br /><br /> public DatabaseLayer getDatabaseLayer(){<br /> return this.mDatabaseLayer;<br /> }<br /><br /> public void generateMonthlyReport(User user){<br /> Report report = mDatabaseLayer.getReport(user);<br /> mPresentationLayer.present(report);<br /> }<br />}<br /><br />public final class HistoricalReportGenerator{<br /> private final ReportGenerator mReportGenerator;<br /><br /> public HistoricalReportGenerator(ReportGenerator reportgen){<br /> this.mReportGenerator = reportgen;<br /> }<br /><br /> public ReportGenerator getReportGenerator(){<br /> return this.mReportGenerator;<br /> }<br /><br /> public void generateHistoricalReport(User user, Duration duration){<br /> Report historicalReport = mReportGenerator.getDatabaseLayer().getReport(user, duration);<br /> mReportGenerator.getPresentationLayer().present(report);<br /> }<br />}<br /></code></pre><p>This approach works fine when the class hierarchy is only a couple of levels deep. If it gets deeper than that, then getting a handle to the members of the base class becomes unwieldy. For example, suppose we have the following:</p><pre class="prettyprint"><code>public class AnnualReportGenerator extends HistoricalReportGenerator<br />public class LeapYearReportGenerator extends AnnualReportGenerator<br /></code></pre><p>Now imagine a method in <code>LeapYearReportGenerator</code> needs access to the <code>DatabaseLayer</code> object. The code for this would look lik:</p><pre class="prettyprint"><code>mAnnualReportGenerator().getHistoricalReportGenerator().getReportGenerator().getDatabaseLayer();<br /></code></pre><p>This is clearly something you want to avoid. With the composition approach, you also lose the runtime polymorphism advantage.</p><h3>Conclusion</h3><p>To summarize what this article discussed:</p><blockquote><ul><li>The easiest way to make a class thread-safe is to make it immutable.</li><li>Strong immutability closes the door on extensibility.</li><li>It is often convenient to make a class weakly immutable. This allows it to be sub-classed.</li><li>If you make an immutable class extensible, clearly establish in the javadoc, the contract that sub-classes must preserve the immutability guarantees.</li></ul></blockquote><p>Other than these observations, we also saw that:</p><blockquote><ul><li>Immutability is not the only way to achieve thread-safety, and in fact immutability is not always desirable.</li><li>Instead of inheriting from a weakly immutable class, one can also extend the functionality by composing a class with a strongly immutable object as its member. This has its own pros and cons - and both approaches must be evaluated before deciding on one.</li></ul></blockquote><script>prettyPrint()</script></description>
<pubDate>Sat, 05 Jan 2013 21:40:00 +0530</pubDate>
<link>/blog/2013/01/05/extensibility-and-immutability-in-java/</link>
<guid isPermaLink="true">/blog/2013/01/05/extensibility-and-immutability-in-java/</guid>
<category>java</category>
<category>thread-safety</category>
<category>immutability</category>
<category>programming</category>
<category>extensibility</category>
</item>
</channel>
</rss>