How do I pass data between Activities in Android application? How do I pass data between Activities in Android application? android android

How do I pass data between Activities in Android application?


In your current Activity, create a new Intent:

String value="Hello world";Intent i = new Intent(CurrentActivity.this, NewActivity.class);    i.putExtra("key",value);startActivity(i);

Then in the new Activity, retrieve those values:

Bundle extras = getIntent().getExtras();if (extras != null) {    String value = extras.getString("key");    //The key argument here must match that used in the other activity}

Use this technique to pass variables from one Activity to the other.


The easiest way to do this would be to pass the session id to the signout activity in the Intent you're using to start the activity:

Intent intent = new Intent(getBaseContext(), SignoutActivity.class);intent.putExtra("EXTRA_SESSION_ID", sessionId);startActivity(intent);

Access that intent on next activity:

String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");

The docs for Intents has more information (look at the section titled "Extras").


Passing Intent extras is a good approach as Erich noted.

The Application object is another way though, and it is sometimes easier when dealing with the same state across multiple activities (as opposed to having to get/put it everywhere), or objects more complex than primitives and Strings.

You can extend Application, and then set/get whatever you want there and access it from any Activity (in the same application) with getApplication().

Also keep in mind that other approaches you might see, like statics, can be problematic because they can lead to memory leaks. Application helps solve this too.