Wednesday, November 21, 2012

Hey rook, abstract activities cannot be launched


I'm not a programming master by any means, but this one felt like a rookie mistake. I was hunting down an InstantiationException. Below is a helper class used to launch a new activity simply by taking in an activity's name in the constructor, then launching that activity in an onClick() event.

public class ActivityLauncher implements OnClickListener {

Class<? extends Activity> mClass;
Bundle mBundle;

public ActivityLauncher(Class<? extends Activity> clazz) {
this(clazz, new Bundle());
}

public ActivityLauncher(Class<? extends Activity> clazz, Bundle bundle) {
mClass = clazz;
mBundle = bundle;
}

@Override
public void onClick(View v) {
launchActivity(v.getContext(), mClass, mBundle);
}

}

The launch activity method comes from another helper class. See that one below:

public static void launchActivity(Context context,
Class<? extends Activity> clazz, Bundle extras) {

Intent intent = new Intent(context, clazz);
intent.putExtras(extras);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}

This structure works great to maintain clean code. Whenver you need to set an onClick() listener that simply launches another class, just new up an instance of ActivityLauncher, passing it the name of the class you want to start. If you need to pass some values to the activity being started, pass in a bundle along with the activity class name. Where did I make a rookie mistake? I passed in an activity that was actually an abstract class. That code compiles, but it leads to InstantiationException, a runtime exception.  It's not quite clear because the constructor is invoked in the tangle of Android source code and not in any code that I've written. I, however, should know that one can't instantiate an abstract class, which also means one can't launch an activity that's defined as an abstract class.

No comments:

Post a Comment