For fragments I have this code to create a new instance:

public static FoodDetails newInstance(Food food) {
    FoodDetails foodDetails = new FoodDetails();
    Bundle args = new Bundle();
    args.putParcelable(FoodConstants.BundleConstants.FOOD_OBJECT, food);
    foodDetails .setArguments(args);
    return foodDetails ;

What I like about this is that I can see what arguments are passed to the fragment.

I want a similar way for Activities so this is my proposed solution.

public class FullScreenImageActivity extends BaseActivity {

public static Intent createIntent(String[] images, String googleAnalyticsCategory,int positionToStartFrom){
    Intent intent = new Intent(MyApplication.getInstance(),FullScreenImageActivity.class);
    intent.putExtra(FoodConstants.BundleConstants.POSITION_TO_START_FROM, positionToStartFrom);
    return intent;

The method returns a built intent and adds the parameters to the bundle Note that MyApplication is a subclass of Application so I am using the application context in the intent argument.

And then you can start the activity like this:

startActivity(FullScreenImageActivity.createIntent(mImages, AnalyticsUtils.CATEGORY_FOOD,position));

The benefits are:

  • Do not need type the bundle keys all the time
  • You can see what arguments are passed to the activity

1 Answer 1


Your solution looks great to me, apply Fragment's instantation to a Class seems to be a good pattern and a nice idea. However, I have just a little tip for this static method: pass the current Context instead of Application Context:

public class SampleActivity extends BaseActivity {
    public static Intent createIntent(Context context, String[] a, String b) {
        Intent intent = new Intent(context, SampleActivity.class);
        intent.putExtra(AppConstants.KEY_ARG_ARRAY,  a);
        intent.putExtra(AppConstants.KEY_ARG_STRING, b);
        return intent;

This allows you to get the right Activity calling the new Intent instead of whole application context. So, the called syntax could be:

startActivity( SampleActivity.createIntent(this, a, b) );
// 'this' being the calling class Context (like 'MainActivity.this' or 'getActivity()')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.