Saturday, 23 November 2013

Activity intent creation


This is a useful little trick I learned from a colleague allows you to give you the intent for an Activity rather than creating the intent in multiple activities, this reduces the chances of mistakes or errors from changes over time and also makes it more OO.

The function should be inside the activity and just take a Context object and whatever else is needed by the activity, it then bundles the extras and returns the intent:



Login Activity

void loginSuccessful(String userToken) {
    startActivity(DashboardActivity.getIntent(LoginActivity.this, userToken));
}


Dashboard Activity

private static final String EXTRA_TOKEN = "user_login_token";
public Intent getIntent(Context ctx, String userToken){
    Intent intent = new Intent(ctx, DashboardActivity.class);
    intent.setExtra(EXTRA_TOKEN, userToken);
    return intent;
}

private String mToken;

public void onCreate(Bundle data){
    ...
    mToken = getIntent().getStringExtra(EXTRA_TOKEN);
}


The benefit of this is that if I now wanted to have a second parameter I can easily add it, either by changes to the function or creating a second one depending on whether or not the new parameter is required or not. 

There are several good reasons for changing to this method, 

  1. It allows a developer to write the getIntent() function, and work on the activity or leave it until later, and allows for another developer to work on the activity that calls it without having to know about or deal with the contents of the Activity at any point. 
  2. It also allows the class to have a small profile as you won't have the EXTRA_* constants visible to other classes, or even worse typing names in every activity. 
  3. It helps to avoid repeated code.

Overall I, and others, have found that while it takes as long to write your code this way and only helps initial development slightly, it makes maintenance and adding additional parameters so much easier and faster. We have yet to find any downsides to this approach.