Skip to content

Passing Information Between Activities

December 26, 2009

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

7 Comments leave one →
  1. Khurram permalink
    April 22, 2012 7:04 am

    That’s really Simple and easy to understand example Specially for the beginners like me……
    great Work
    Keep it up…….

  2. shambhu permalink
    June 10, 2012 11:24 pm

    really nice example

  3. ilja permalink
    October 4, 2012 5:39 am

    Nice. I hope there’s a way to pass more complex objects between activities.

  4. November 8, 2012 2:57 am

    understandable example of passing information between activities.. its good intent to put simple android example like this.. thanks 🙂

Trackbacks

  1. Think Android

Leave a comment