2

When creating a fragment, it´s recommended to use a static method inside the fragment class also to pass and wrap arguments (s.this post).

Now I thought about sth similar for starting an activity with an intent.

f.e.:

public class ItemDetailActivity extends AppCombatActivity {

    public static final String ARG_PARAM1 = "param1";
    public static final String ARG_PARAM2 = "param2";

    public static void startAsIntent(Context context, String param1, int param2) {
        Bundle extras = new Bundle();

        extras.putString(ARG_PARAM1, param1);
        extras.putInt(ARG_PARAM2, param2);

        Intent intent = new Intent(context, ItemDetailActivity.class);
        intent.putExtras(extras);

        context.startActivity(intent);
    }
}

Is this a good idea?

Community
  • 1
  • 1
monty.py
  • 2,511
  • 1
  • 17
  • 29
  • 2
    There's nothing wrong with it that I know of. Others have suggested doing the same thing. It has the advantage of allowing you to perform more validation before setting up the extras (e.g., checking the size of a `Bitmap` so you know that you won't go over the 1MB IPC transaction limit). – CommonsWare Mar 01 '16 at 21:47
  • 1
    I've done it this way with no issues. Especially if the Activity *needs* the parameters that you're passing in. It shows explicitly what is needed so it's far less confusing. – DeeV Mar 01 '16 at 21:52
  • 1
    I've seen this quite a bit. I actually like it if there's complex logic to filling in the extras that would otherwise need to be repeated multiple places. – Gabe Sechan Mar 01 '16 at 21:55
  • 1
    I think just calling the method `start` is more concise because you aren't starting an Activity "as an Intent", you are using the Intent simply to "start" the Activity – OneCricketeer Mar 02 '16 at 04:19

2 Answers2

3

This is completely correct, maybe the misunderstanding is caused because the data bundle must be received by the Activity. And now since some API´s ago we have fragments and sometimes is necessary open an activity ( and send a bundle with data) from the Fragment.

Jorgesys
  • 124,308
  • 23
  • 334
  • 268
-1

You can use direct pass data to intent ,bundle best use for fragment, Check following example

Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putString(ARG_PARAM1 ,value); 
intent.putInt(ARG_PARAM2 ,value); 

I hope help this

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Rathod Vijay
  • 417
  • 2
  • 7
  • i know, but i needed to put a serializable, so i used a bundle. To show you an example I changed the code and stayed with the bundle. – monty.py Mar 02 '16 at 18:50