-2

I have seen some Intent declarations on Youtube, Stack Overflow and elsewhere, and I have found two types of Intent declarations.

First type :

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);

Second type :

startActivity(new Intent(FirstActivity.this, SecondActivity.class));

My question is which is the better way to declare Intent? Is there any significant difference between the two declarations?

skomisa
  • 16,436
  • 7
  • 61
  • 102
cleanrun
  • 549
  • 6
  • 20

3 Answers3

2

There is no difference in performance, it depends on your preference actually. Personally, I prefer the first option because assigning Intent to a new variable is clearer and I can easily add more extras later.

Bach Vu
  • 2,298
  • 1
  • 15
  • 19
2

This is mostly preference. Which is easier to read/understand? I always use the first.

If you ever need to add intent extras or set it's action, you'll want to go with the first anyway.

AzraelPwnz
  • 506
  • 2
  • 12
1

It will work the same but if you want to set flag of activity launch or you want to put some values/objects in Intent for sending to target activity, the first way will be more clear and easily understandable. eg.

    // First type
    Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("name","xyz");
    intent.putExtra("email","abc@gmail.com");
    startActivity(intent);

    // Second type
     startActivity(new Intent(FirstActivity.this, SecondActivity.class)
    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    .putExtra("name","xyz")
    .putExtra("email","abc@gmail.com"));
Hemendra Gangwar
  • 491
  • 5
  • 18