Saturday, June 8, 2013

Android ListViews: "Hybrid" Choice Behavior

The goal of this post is to use a ListView in a master/detail configuration where both of the following are possible:

  1. Touch a single item to open it.
  2. Long-tap multiple items to choose them and perform a common action on them.

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.

This behavior (with some minor variations) is seen in apps like GMail, Google Play Store and the Google I/O 2013 app.

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)

This is what we want to achieve

A note on the terminology

Just to avoid confusion, let's sort of formalize the terminology related to the states an item in the list can be in.

An item is opened when the user is viewing the details about that item. In other words, the details of that item are being displayed in the DetailFragment. In dual-pane mode, there needs to be some visual indication in the ListView to let the user know which one of the items is currently opened.

When an item is chosen, 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 ListView 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.

Implementation

You might notice that one can achieve the opened behavior using ListView's CHOICE_MODE_SINGLE and the chosen behavior using CHOICE_MODE_MULTIPLE_MODAL. 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 CHOICE_MODE_MULTIPLE_MODAL, then you lose the ability to visually indicate the currently opened item.

The solution I ended up with was to not rely on the CHOICE_MODE_MULTIPLE_MODAL, but rather simulate it myself. The high level steps are as follows:

  1. Create a custom ListAdapter that keeps track of the currently opened item and the currently chosen items
  2. In the getView() (or equivalent) method of your custom ListAdapter, examine the item at the supplied position. If it is the currently opened item, set its visual properties to indicate this. Ditto if it is one of the chosen items.
  3. Listen for clicks and long clicks on your ListView and update the adapter defined in step 1 accordingly- i.e., in your OnItemClickListener implementation, set the opened item and in OnItemLongClickListener, update the list of chosen items.
  4. OnItemLongClickListener is also where you need to start the action mode (getListView().startActionMode()) if it isn't started already.

HybridChoiceAdapter

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.

    /* Keep track of currently opened item and chosen items */
    private Set<Integer> chosenItems = new HashSet<Integer>();
    private int openedItem = -1;

    //...snip...

    public void setItemChosen(int position, boolean chosen) {
        if (!chosen && isItemChosen(position)) {
            chosenItems.remove(position);
        } else if (chosen && !isItemChosen(position)) {
            chosenItems.add(position);
        }
    }

    public boolean isItemChosen(int position) {
        return chosenItems.contains(position);
    }

    public Set<Integer> getChosenItems() {
        return chosenItems;
    }

    public void setOpenedItem(int position) {
        this.openedItem = position;
    }

    public int getOpenedItem() {
        return this.openedItem;
    }

    public boolean isItemOpened(int position) {
        return this.openedItem == position;
    }

    public void clearChoices() {
        chosenItems.clear();
    }

    public void toggleItem(int position) {
        if (isItemChosen(position)) {
            chosenItems.remove(position);
        } else {
            chosenItems.add(position);
        }
    }

    public int getChosenItemsCount(){
        return this.chosenItems.size();
    }

The getView() method

At this point, we have set up the Adapter 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.

    @Override
    public final View getView(final int position, View convertView,
            ViewGroup parent) {
        View v = convertView;
        /*Normal procedure to inflate the row layout and set its properties goes here*/

        v.setBackgroundResource(0);
        if (isItemOpened(position)) {
            setViewAsOpened(v); //This method sets the appropriate background resource or drawable
        }

        if (isItemChosen(position)) {
            setViewAsChosen(v);//This method sets the appropriate background resource or drawable
        }

        return v;
    }

Listening for clicks on the ListView

In your Activity or Fragment, 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 ListAdapter that also implements OnItemLongClickListener.

    @Override
    public void onListItemClick(ListView listView, View view, int position, long id) {
        super.onListItemClick(listView, view, position, id);

        //When an item is clicked, set it as the opened item
        mAdapter.setOpenedItem(position);

        //At this point, clear all choices
        mAdapter.clearChoices();
        if(mActionMode != null){
            mActionMode.finish();
        }
        mAdapter.notifyDataSetChanged();

         // code to show the details fragment goes here
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

        //When an item is long clicked, toggle its chosen state
        //Also update the CAB title to reflect the change in number of chosen items
        mAdapter.toggleItem(position);
        updateActionMode();
        return true;
    }

    private void updateActionMode(){
        if(mActionMode == null){
            mActionMode = getListView().startActionMode(actionModeCallback);
        }

        mActionMode.setTitle(String.format("%d chosen", mAdapter.getChosenItems().size()));
        mAdapter.notifyDataSetChanged();
    }

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.

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.

Variations

There are subtle variations of what action the user has to take to choose an item. For example,

  • 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.
  • 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, even single clicking on other items chooses them. This is different from our implementation where a single-tap always opens an item.

You will need to modify the code for the click listeners if you want to go with one of these variations. The ListAdapter code itself should remain the same.

Turning this into a library?

Well, I gave this a thought too. Exposing the custom Adapter as a library is the easy part. What I couldn't decide upon is how to include the ListView listeners in a library. Developers might wish to extend ListActivity or ListFragment or simply include a ListView 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 Sherlock counterparts!)

If anyone has any ideas on how this could be library-ized, please do drop a comment.

GitHub repositroy

The complete source code for this article is available as a sample project on GitHub here.

Saturday, March 9, 2013

Shift to Octopress Postponed

For some time now, I have been toying with the idea of migrating this blog to octopress. 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 - Fabric - to use as my base theme.

However, it looks like I'm going to have to postpone migration to Octopress. Here are some of the reasons:

Redirection

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 .blogspot domain.

Comments

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.

Importing

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:

  • Syntax Highlighting: 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 post generation time. 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.

  • Permalinks: 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.

Looking Forward

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.

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.

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.

So, in a nutshell:

I will surely be migrating to a static site generator like octopress in the near future. But for now, I'm sticking with blogger.


Monday, February 18, 2013

Android Constants: Preference Keys, Actions, Extras and more

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!

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 Strings. Consider this sampling:

  • Keys for SharedPreferences are Strings
  • Keys for Bundles are Strings
  • Intent extras are Bundles, and hence, if you want to include any extras or retrieve them from Intents, you use their String keys to work with them. Ditto with Fragment arguments
  • Intent and IntentFilter actions (and categories) are Strings themselves
  • . . .

I used to deal with these the lazy way: Declare the keys as public static 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:

  • The class that broadcasts an Intent
  • The class that creates or sends a non-broadcast Intent (this might be an Activity or Service for example)
  • The class that creates a SharedPreference for editing

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?

if(AbstractBaseLiveModeActivity.ACTION_LIVE_UPDATE.equals(intent.getAction())){
    Bundle extras = intent.getExtras();
    if(extras.containsKey(AbstractBaseLiveModeActivity.EXTRA_LIVE_UPDATE_TIMESTAMP)){
        long timestamp = extras.getLong(AbstractBaseLiveModeActivity.EXTRA_LIVE_UPDATE_TIMESTAMP);
        // Do something with timestamp here
    }
}

Constants Almighty

One common solution to this problem is to put everything into one "God" object called Constants or whatever, and prefix the constant names with EXTRA_, ACTION_ or other such descriptive characters to keep them distinct.

public class Constants{
    private Constants(){}

    public static final String ACTION_LIVE_UPDATE = "com.myawesomeapp.action.LIVE_UPDATE";
    // ...

    public static final String EXTRA_LIVE_UPDATE_TIMESTAMP = "com.myawesomeapp.extra.LIVE_UPDATE_TIMESTAMP";
    // ...

}

Now, we've solved the readability problem since we just qualify the constant names with Constant. So, all's well, right?

Wrong!

The problem with this approach is as the number of extras, actions and preference keys increases, the Constants class quickly becomes unmanageable. Also, having to use the ACTION_ and EXTRA_ prefixes hinders usability with some IDE's. For example, with Eclipse, even if you know that you want EXTRA_LIVE_UPDATE_TIMESTAMP, you are forced to type the first six characters without which the code assist will not be able to filter only the extras.

Try using Eclipse to find a particular action or extra from the Intent class if you want to see a real-world example of what I mean.

Split it up into distinct constant files

Here's what I do to keep my code free of such stutter. I simply split up the "God" Constants class into several smaller, easier-to-manage constants classes. Like so:

public class Extras{
    private Extras(){}

    private static String createExtra(String suffix){
        return Constants.NAMESPACE_PREFIX + ".extra."+suffix; //NAMESPACE_PREFIX could be "com.myawesomeapp"
    }

    public static final String LIVE_UPDATE_TIMESTAMP = createExtra("LIVE_UPDATE_TIMESTAMP");
    public static final String LIVE_UPDATE_VALUE = createExtra("LIVE_UPDATE_VALUE");
    public static final String FRIEND_ID = createExtra("FRIEND_ID");
    // ...

}

public class Broadcasts{
    private Broadcasts(){}

    private static String createBroadcast(String suffix){
        return Constants.NAMESPACE_PREFIX + ".broadcast."+suffix; //NAMESPACE_PREFIX could be "com.myawesomeapp"
    }

    public static final String LIVE_UPDATE = createBroadcast("LIVE_UPDATE");
    public static final String FRIEND_OFFLINE = createBroadcast("FRIEND_OFFLINE");
    // ...
}

public class Actions{
    private Actions(){}

    private static String createAction(String suffix){
        return Constants.NAMESPACE_PREFIX + ".action."+suffix; //NAMESPACE_PREFIX could be "com.myawesomeapp"
    }

    public static final String JOIN_CHAT = createAction("JOIN_CHAT");
    // ...
}

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, this code snippet changes to:

if(Broadcasts.LIVE_UPDATE.equals(intent.getAction())){
    Bundle extras = intent.getExtras();
    if(extras.containsKey(Extras.LIVE_UPDATE_TIMESTAMP)){
        long timestamp = extras.getLong(Extras.LIVE_UPDATE_TIMESTAMP);
        // Do something with timestamp here
    }
}

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.

Wait, what about constants in XMLs?

Glad you asked. In android, many of these constants are used not only in Java code, but also from XML files.

  • Preference keys can be referenced in preferences XML files via the <PreferenceScreen> element.
  • Intents can be declared in AndroidManifest.xml. This means, the Intent action and categories can be referenced from the manifest.
  • BroadcastReceivers can be declared in AndroidManifest.xml. The <intent-filter> action and categories are referenced here.
  • . . .

This presents a problem since we end up duplicating the constants here. We cannot use our Broadcasts.LIVE_UPDATE constant in XML, so we tend to repeat the constant value:

<intent-filter>
    <action android:name="com.myawesomeapp.broadcast.LIVE_UPDATE"/>
</intent-filter>

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.

Using String resources to avoid duplication

One way to avoid constant literal duplication issue explained in the previous section is to use string resources. 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.

To keep things clean, you could keep these constants in their own file under values/ folder - for example constants.xml. In there, you could add

<resources>

    <!-- Broadcast Actions -->
    <string name="broadcast_live_update">com.myawesomeapp.broadcast.LIVE_UPDATE</string>
    <string name="broadcast_friend_offline">com.myawesomeapp.broadcast.FRIEND_OFFLINE</string>

    <!-- Intent Extras -->
    <string name="extra_live_update_timestamp">com.myawesomeapp.extra.LIVE_UPDATE_TIMESTAMP</string>
    <string name="extra_live_update_value">com.myawesomeapp.extra.LIVE_UPDATE_VALUE</string>
    <string name="extra_friend_id">com.myawesomeapp.extra.FRIEND_ID</string>

    <!-- Preference Keys -->
    <string name="pref_key_update_interval">UPDATE_INTERVAL</string>
    <string name="pref_key_theme">THEME</string>

</resources>

Then, you could access these values from XML as follows:

<intent-filter>
    <action android:name="@string/broadcast_live_update"/>
</intent-filter>

<Preference 
    android:key="@string/pref_key_update_interval"
    ... />

UPDATE Jun 2015: This does not work. The android:name attribute does not take a string resource. It MUST be a string itself. The approach works for Preferences though

And so on. In Java code, you'd access these as:

if(getString(R.string.broadcast_live_update).equals(intent.getAction())){
    // ...
}

mSharedPref.getLong(getString(R.string.pref_key_update_interval));

Unfortunately, this solution has all the disadvantages I mentioned in an earlier section.

Your constants.xml will quickly become a monolithic clutter. This can be addressed by creating a separate XML file for each type of constant - like broadcasts.xml, pref_keys.xml etc. Even if you do that, you will still be accessing all the resources using @string/blah and R.string.blah.

Also, IDE content assist is still a problem. Your resource names will need to be prefixed with action_ or broadcast_ or pref_key_ etc and finding the key you need could be frustrating.

A workable strategy

Here's a strategy I follow to decide how I should declare these constants:

  • For preference keys, prefer string resources. This is because you are most likely to be building your Settings screens with XML anyway.
  • For all other key constants, prefer split constant files.
  • Only if you need to use these from XML, declare them as string resources.

Friday, February 1, 2013

Android: Passing an arbitrary object to a custom View

So, I came across a situation where I wanted to create a custom View in Android (let's call it MyAwesomeView). I had to work with a couple of constraints:

  1. I have to be able to pass in an additional object to MyAwesomeView.
  2. The MyAwesomeView should also be usable from XML.
  3. The MyAwesomeView should be distinct from the application itself - i.e., it should be possible to distribute the MyAwesomeView as a library.

To elaborate a bit on the "pass in an additional object" part: View provides three standard constructors using which you can pass in

  • a Context,
  • an AttributeSet and
  • an int representing the style.

I want to also pass in a BitmapCache object since MyAwesomeView uses lots of Bitmaps and I don't want to encounter the dreaded OutOfMemoryError that goes hand in hand with decoding large bitmaps in an Android app. MyAwesomeView decodes a bitmap only if it is not already present in the cache.

The second constraint makes things really difficult. It is possible to pass in additional "configuration" information to a View by creating custom attributes. However, this obviously cannot be used to pass in an object like a BitmapCache.

Augmenting the Context object with additional information

This solution I came across is as follows:

  • Define an interface BitmapCacheProvider with a single method provideBitmapCache();
  • Make your Activity class implement the interface defined in step 1. Override the interface method to return an appropriate BitmapCache object.
  • In the constructor of MyAwesomeView, check to see if the context object passed in to implements the BitmapCacheProvider interface. If it does - we're good. If not, then fail fast (or disable cacheing - whatever works for you).

In code, here's what this would look like:

/**
 * Interface to be implemented by the Context (Activity etc) in which `MyAwesomeView` runs
 */
public interface BitmapCacheProvider{
    BitmapCache provideBitmapCache();
}

/**
 * An example of an Activity that implements BitmapCacheProvider
 */

public class MyActivity extends Activity implements BitmapCacheProvider{
    //... Life-cycle methods of the Activity here

    @Override
    public BitmapCache provideBitmapCache(){
        //Get your instance of bitmapcache here - probably from your Application
        BitmapCache bitmapCache = ...;
        return bitmapCache;
    }
}

/**
 * Custom View that uses an additional object (BitmapCache) for its configuration.
 */
public class MyAwesomeView extends View{
    private BitmapCache mBitmapCache;

    public MyAwesomeView(Context context){
        init(context, null, 0);
    }

    public MyAwesomeView(Context context, AttributeSet attrs){
        init(context, attrs, 0);
    }

    public MyAwesomeView(Context context, AttributeSet attrs, int style){
        init(context, attrs, style);
    }

    private void init(Context context, AttributeSet attrs, int style){
        try{
            /*
             * Try casting the contex to BitmapCacheProvider. 
             * 
             * If the required interface is not implemented, 
             * it'll throw a ClassCastException
             */
            mBitmapCache = ((BitmapCacheProvider) context).provideBitmapCache();
        } catch(ClassCastException e){
             throw new ClassCastException(context.toString()
                    + " must implement BitmapCacheProvider");
        }

        //At this point, we have the BitmapCacheObject which we can use for further processing.
    }

}

Conclusion:

What we saw in this post was how it is possible to create a custom View 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:

  • In this example, I just augmented the main Activity with the desired interface, but you might need to do this for other classes. Basically, the Context that is passed in to the custom View constructor must be enhanced to implement the interface. What this context is depends on how you are including the custom View.
  • You might argue that the BitmapCache should be part of the custom View 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!

Tuesday, January 29, 2013

Android: is onDestroy the new onStop?

Conventional Android development logic dictates that if there is some action you want to perform (or rather, stop performing) when your Activity is no longer visible to the user, do it in onStop(). Likewise, if there is some action you want to restart performing when the user restarts interacting with your Activity, do it in onStart(). The disadvantage of this approach, of course, is that it wouldn't play well with device orientation changes.

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 onStop(), to onDestroy().

A trivial (incorrect) example

public TrivialIncorrectActivity extends Activity{

    //onCreate() and other life-cycle overrides like onResume() go here ...

    @Override public void onStart(){
        super.onStart();
        startMakingThatPeriodicRestCall();
    }

    @Override public void onStop(){
        super.onStop();
        stopMakingThatPeriodicRestCall();
    }

    // ... Other life-cycle overrides like onDestroy() go here

}

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.

setRetainInstance to the rescue . . .

API 11 introduced the Fragment API, and along with it, the setRetainInstance method, which is also usable with older versions of Android by means of the support library. You can go through the documentation to understand the effect of a setRetainInstance(true). Essentially, when a configuration change is happening, even though the hosting Activity is being re-created, the Fragment instance is not destroyed.

So, this allows us to improve upon our previous example.

public IncorrectRotationTolerantActivity extends FragmentActivity{

    private static final String TAG_RETAIN_FRAGMENT = "RetainFragment";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState == null){
            getSupportFragmentManager().beginTransaction()
                .add(IncorrectRetainFragment.newInstance(), TAG_RETAIN_FRAGMENT).commit();
        }
    }
}

public class IncorrectRetainFragment extends Fragment{

    public IncorrectRetainFragment(){}

    public static IncorrectRetainFragment newInstance(){
        IncorrectRetainFragment frag = new IncorrectRetainFragment();
        frag.setRetainInstance(true);
        return frag;
    }

    @Override
    public void onStart() {
        super.onStart();
        startMakingThatPeriodicRestCall();
    }

    @Override
    public void onStop() {
        super.onStop();
        stopMakingThatPeriodicRestCall();
    }

}

This code snippet still doesn't do what we want it to do. It does not prevent re-making that REST call during orientation changes. Why?

Because, setRetainInstance doesn't prevent a Fragment's onStop() from being called - it just prevents onDestroy() from being called. So, even if you ask for a Fragment instance to be retained across configuration changes, the onStop() method of the Fragment is always still called when the device is rotated.

onDestroy() is the new onStop()

To fix the problem, postpone stopping the REST call to the onDestroy() of the Fragment. Similarly, start making the call in onCreate() instead of in onStart(), since onCreate() is not called when the device is rotated, but onStart() is.

public RotationTolerantActivity extends FragmentActivity{

    private static final String TAG_RETAIN_FRAGMENT = "RetainFragment";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState == null){
            getSupportFragmentManager().beginTransaction()
                .add(RetainFragment.newInstance(), TAG_RETAIN_FRAGMENT).commit();
        }
    }
}

public class RetainFragment extends Fragment{

    public RetainFragment(){}

    public static RetainFragment newInstance(){
        RetainFragment frag = new RetainFragment();
        frag.setRetainInstance(true);
        return frag;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onStart(savedInstanceState);
        startMakingThatPeriodicRestCall();
    }

    @Override
    public void onDestroy() {
        super.onStop();
        stopMakingThatPeriodicRestCall();
    }

}

This seems so semantically wrong though. onDestroy() represents the end of the entire lifetime of an Activity/Fragment and what we really wanted to do was monitor the visible lifetime. Also, there is no guarantee that onDestroy() 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.

A more correct, more restrictive solution:

There exists another solution to this problem - but it works only on API 11 and later, because it uses methods introduced in API 11 - isChangingConfigurations() and getChangingConfigurations().

public RotationTolerantActivity extends FragmentActivity{

    private boolean mRotated;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Boolean nonConfigState =
            (Boolean)getLastCustomNonConfigurationInstance();
        if (nonConfigState == null) {
            mRotated = false;
        } else {
            mRotated = nonConfigState.booleanValue();
        }
    }

    @Override 
    public void onStart(){
        super.onStart();
        if(!mRotated){
            startMakingThatPeriodicRestCall();
        }
    }

    @Override
    public void onStop(){
        super.onStop();
        mRotated = false;
        if (isChangingConfigurations()) {
            int changingConfig = getChangingConfigurations();
            if ((changingConfig & ActivityInfo.CONFIG_ORIENTATION) == ActivityInfo.CONFIG_ORIENTATION) {
                mRotated = true;
            }
        }

        if(!mRotated){
               stopMakingThatPeriodicRestCall();
        }
    }

    @Override
    public Object onRetainCustomNonConfigurationInstance() {
            return mRotated ? Boolean.TRUE : Boolean.FALSE;
        }

}

This solution is semantically correct, and works as expected. However, it only works on API 11 and higher, even though we extend FragmentActivity from the support library .

Bonus: Why onStop() and not onPause()?

The keen reader would have observed that this post talks about stopping un-needed tasks in onStop()and not onPause() - even though onPause() is the only one of these methods that is guaranteed to be called. Remember that after onPause() is called, the process could be killed in order to reclaim memory and thus onStop() and onDestroy() might never be called.

Yet, this entire post insists on using onStop() to stop un-needed tasks. The reason for this lies in the technique used in my library android-app-pause. Unfortunately, this library in its current form does not handle device orientation changes correctly. This will be fixed in a future release though.

Saturday, January 5, 2013

Extensibility and Immutability in Java

Objective:

To devise a way to make thread-safe, a Java class designed to be extensible.

Introduction:

Effective Java, Second Edition: Item 15 says "Minimize Mutability". One should always try to make a class immutable. This has several advantages that I will not go over here (Since Effective Java explains it all). I will however point out one of those advantages since it is central to this discussion:

Making a class immutable is the easiest way to ensure that the class is thread-safe.

There is however a problem: to make a class truly immutable, you must prevent it from being sub-classed. Either the class must be declared final, or it should have a private constructor and provide static factory methods instead of constructors. The reasons for this are outlined in Effective Java. The basic premise is that a sub-class can violate the immutability guarantees.

This must-not-be-subclassed restriction may be fine if you are applying immutability to some value object like User, Point, Account etc. However, the same requirement turns out to be overly restrictive if you are applying the concept to logic classes. This is because logic classes are often meant to be customized by extension.

A strongly-immutable logic class:

As an example of a logic class, consider the following ReportGenerator:

public final class ReportGenerator{
    private final DatabaseLayer mDatabaseLayer;
    private final PresentationLayer mPresentationLayer;

    public ReportGenerator(DatabaseLayer db, PresentationLayer pres){
        this.mDatabaseLayer = db;
        this.mPresentationLayer = pres;
    }

    public void generateMonthlyReport(User user){
        Report report = mDatabaseLayer.getReport(user);
        mPresentationLayer.present(report);
    }
}

The other classes have been ommitted for brevity. Assume that DatabaseLayer and PresentationLayer classes are themselves immutable. This makes ReportGenerator strongly immutable and hence, thread-safe.

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 ReportGenerator. Unfortunately, we cannot do this since in order to make ReportGenerator immutable, we have declared it final. One possible approach to solving this issue is making ReportGenerator weakly immutable. This is discussed in the next section.

A weakly-immutable logic class:

One can relax the restriction that an immutable class must not be extensible, while still maintaining the guarantees, provided the sub-class adheres to the established contract. This is done by removing the final modifier from the class declaration, and making all fields protected final, or keep them private final and provide getters which we then use in the sub-classes. Both these approaches are shown in the code below.

public class ReportGenerator{
    protected final DatabaseLayer mDatabaseLayer; //protected field approach
    private final PresentationLayer mPresentationLayer; //private field with accessor approach

    public ReportGenerator(DatabaseLayer db, PresentationLayer pres){
        this.mDatabaseLayer = db;
        this.mPresentationLayer = pres;
    }

    public PresentationLayer getPresentationLayer(){
        return this.mPresentationLayer;
    }

    public void generateMonthlyReport(User user){
        Report report = mDatabaseLayer.getReport(user);
        mPresentationLayer.present(report);
    }
}

We can now sub-class this as follows:

public class HistoricalReportGenerator extends ReportGenerator{

    public HistoricalReportGenerator(DatabaseLayer db, PresentationLayer pres){
        super(db, pres);
    }

    public void generateHistoricalReport(User user, Duration duration){
        Report historicalReport = mDatabaseLayer.getReport(user, duration);
        getPresentationLayer().present(historicalReport);
    }
}

We could also have added more protected final fields to the sub-class if needed.

What we now have is a weakly immutable class. This class is immutable as long as sub-classes adhere to the contract. It is a good idea to establish in the class javadoc, the expectation that sub-classes MUST 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.

Here's an example to how to establish this contract:

/**
 * The logic class that generates the report.
 * ... ...
 * <br/><br/>
 * This class is <em>weakly immutable</em>. It has been kept open for 
 * extensibility. Sub-classes <strong>MUST</strong> preserve the immutability 
 * guarantees of this class. In particular, they must have only immutable 
 * fields; and must not override any of the methods defined in this class to
 * return a mutable reference.
 *
 */

public class ReportGenerator{
    //Class body omitted.
}

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.

Thread-safety is more than Immutability:

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 Java Concurrency In Practice for details on this topic.

Extending the logic class by Composition:

There exists an alternative way to extend the functionality of ReportGenerator that does not involve inheriting from it: "Favor Composition over Inheritance" (Effective Java, Second Edition, Item 16). For completeness, I present the code for this approach here. Do note that this example uses the strongly immutable form of ReportGenerator.

public final class ReportGenerator{
    private final DatabaseLayer mDatabaseLayer;
    private final PresentationLayer mPresentationLayer;

    public ReportGenerator(DatabaseLayer db, PresentationLayer pres){
        this.mDatabaseLayer = db;
        this.mPresentationLayer = pres;
    }

    public PresentationLayer getPresentationLayer(){
        return this.mPresentationLayer;
    }

    public DatabaseLayer getDatabaseLayer(){
        return this.mDatabaseLayer;
    }

    public void generateMonthlyReport(User user){
        Report report = mDatabaseLayer.getReport(user);
        mPresentationLayer.present(report);
    }
}

public final class HistoricalReportGenerator{
    private final ReportGenerator mReportGenerator;

    public HistoricalReportGenerator(ReportGenerator reportgen){
        this.mReportGenerator = reportgen;
    }

    public ReportGenerator getReportGenerator(){
        return this.mReportGenerator;
    }

    public void generateHistoricalReport(User user, Duration duration){
        Report historicalReport = mReportGenerator.getDatabaseLayer().getReport(user, duration);
        mReportGenerator.getPresentationLayer().present(report);
    }
}

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:

public class AnnualReportGenerator extends HistoricalReportGenerator
public class LeapYearReportGenerator extends AnnualReportGenerator

Now imagine a method in LeapYearReportGenerator needs access to the DatabaseLayer object. The code for this would look lik:

mAnnualReportGenerator().getHistoricalReportGenerator().getReportGenerator().getDatabaseLayer();

This is clearly something you want to avoid. With the composition approach, you also lose the runtime polymorphism advantage.

Conclusion

To summarize what this article discussed:

  • The easiest way to make a class thread-safe is to make it immutable.
  • Strong immutability closes the door on extensibility.
  • It is often convenient to make a class weakly immutable. This allows it to be sub-classed.
  • If you make an immutable class extensible, clearly establish in the javadoc, the contract that sub-classes must preserve the immutability guarantees.

Other than these observations, we also saw that:

  • Immutability is not the only way to achieve thread-safety, and in fact immutability is not always desirable.
  • 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.