Another New Year and like many other bloggers I’m thinking about resolutions of writing on my blog more often. Actually, my resolutions are a little grander then just this blog, but I’m still ironing them out.
So instead of going into my life/work goals of 2011 I’d rather share a code snippet/Android pattern I’ve been using quite a bit lately. It grew from working with other Android developers and wanting to specify a mini API for opening an Activity. Many Activities pass data when they open another Android Activity; using Intents, name/value pairs can be defined for the data elements. One problem is though, you must use code inspection to determine what data is passed in, and what the format it is. What I’ve started to do is use a static method in the Activity as a means of starting it. Here’s a simple code snippet to demonstrate what I’m talking about
public class ActivityOne extends Activity
{
private static final String VALUE1 = "value1_param";
private static final String VALUE2 = "value2_param";
public static void startMe( Context ctx, int val1, String val2 )
{
Intent intent = new Intent( ctx, ActivityOne.class );
intent.putExtra( VALUE1, val1 );
intent.putExtra( VALUE2, val2 );
ctx.startActivity( intent );
}
private int _value1;
private String _value2;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_one );
Bundle extras = getIntent().getExtras();
if ( extras != null )
{
_value1 = extras.getInt( VALUE1 );
_value2 = extras.getString( VALUE2 );
}
}
}
This way ActivityOne can be started from another Android Activity using the following call,
ActivityOne.startMe( this, 123, "abc" );
This places the actual means of defining the Intent for ActivityOne in one place, and if this contract is changed, ie adding another variable or changing types, it can be changed in the method signature of startMe and all the places this is called will fall out using a coding tool like Eclipse.
Hope this little snippet can give you some ways on writing cleaner Android code, Happy New Years!