3
\$\begingroup\$

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.LIST_OF_IMAGES_TO_DISPLAY,images);
    intent.putExtra(FoodConstants.BundleConstants.GOOGLE_ANALYTICS_CATEGORY,googleAnalyticsCategory);
    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
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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()')
\$\endgroup\$

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.