Thursday, May 5, 2011

Passing a Bundle on startActivity()?

What's the correct way to pass a bundle to the activity that is being launched from the current one? Shared properties? TIA.

From stackoverflow
  • You can use the Bundle from the Intent:

    Bundle extras = myIntent.getExtras();
    extras.put*(info);
    

    Or an entire bundle:

    myIntent.putExtras(myBundle);
    

    Is this what you're looking for?

    alex : And from the resulting intent you call getIntent().getExtras().get*() to get what's been stored before.
  • You have a few options:

    1) Use the Bundle from the Intent:

    Intent mIntent = new Intent(this, Example.class);
    Bundle extras = mIntent.getExtras();
    extras.putString(key, value);
    

    2) Create a new Bundle

    Intent mIntent = new Intent(this, Example.class);
    Bundle mBundle = new Bundle();
    mBundle.extras.putString(key, value);
    mIntent.putExtras(mBundle);
    

    3) Use the putExtra() shortcut method of the Intent

    Intent mIntent = new Intent(this, Example.class);
    mIntent.putExtra(key, value);
    


    Then, in the launched Activity, you would read them via:

    String value = getIntent().getExtras().getString(key)
    

    NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.

0 comments:

Post a Comment