Whats the difference between pass the variables like this:
Intent intent = new Intent(mCtx, DetailsActivity.class);
intent.putExtra("pId", id);
intent.putExtra("pType", type);
mCtx.startActivity(intent);
and using the keyword Bundle
?
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
// Now let's Pass data using Bundle
Bundle bundle = new Bundle();
bundle.putString("pId", id);
bundle.putString("pType", type;
intent.putExtras(bundle);
startActivity(intent);
Im new to Android development and I am curious to which method is better or stadard when doing android development?
3
Answers
Intent
Bundle
putExtras does not put your bundle inside Intent. Instead, it copies it over to the current intent bundle.
The first method is recommended. All samples are using the first putExtra (key, value) methods.
In most scenarios you should know what you are passing to the next activity, so putExtra ( key, value ) makes sense because you know what the key is.
The only scenario I can think of to use the second method is a transient activity which receives bundle from previous activity and need to pass all information to next activity. The transient activity does not need to know what is being passed and just pass everything it received to the next activity.
BTW, if you create your own Bundle, put the key values in and then call putExtra ( bundle), there is extra cost for the temporary bundle so it is less efficient.
One puts the keys directly and one puts them in a Bundle first. The end result is the same.
The first is "better" or more "standard" simply because it eliminates the need to create the bundle yourself first – it’s a redundant step. You’d really only ever need to use that method if your code already had some logic that maintained a
Bundle
of data that you wanted to pass along in anIntent
as key / value pairs.