skip to Main Content

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


  1. Intent

    public Intent putExtra(String name, String value) { 
      if (mExtras == null) { 
            mExtras = new Bundle(); 
         } 
        mExtras.putString(name, value); 
        return this; 
    }
    

    Bundle

    public void putString(String key, String value) { 
        unparcel(); 
         mMap.put(key, value);
     }
    

    putExtras does not put your bundle inside Intent. Instead, it copies it over to the current intent bundle.

    public Intent putExtras(Bundle extras) { 
        if (mExtras == null) { 
           mExtras = new Bundle(); 
        } 
        mExtras.putAll(extras); 
        return this; 
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. Whats the difference between pass the variables like this and using the keyword Bundle?

    One puts the keys directly and one puts them in a Bundle first. The end result is the same.

    Im new to Android development and I am curious to which method is better or stadard when doing android development?

    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 an Intent as key / value pairs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search