Saturday, December 26, 2009

Passing Information Between Activities

Hey everyone,

Here’s a little short blurb on how to pass information between Activities (I know this is probably documented, but at least for me it always helpful to see small examples in action):

public class A extends Activity { @Override public void onCreate(Bundle savedInstanceState) { // code here Intent i = new Intent( this, B.class ); i.putExtra( "int", 5); i.putExtra( "string", "hello" ); startActivity( i ); } }

And here’s the code for Class B:

public class B extends Activity { @Override public void onCreate(Bundle savedInstanceState) { // code here Intent i = getIntent(); int number = i.getIntExtra("int", -1); String str = i.getStringExtra("string"); // number = 5 // str = "hello" } }

So basically the idea is you pass the intent to Class B and the intent acts like a standard Map object. For getIntExtra, if the app can’t find the value with key “integer”, then -1 is returned as the default, and for getStringExtra, if the app can’t find the key then null is returned.

Happy Coding.

- jwei

[Via http://thinkandroid.wordpress.com]

No comments:

Post a Comment