How do I pass data between Activities in Android application?
I have a scenario where, after logging in through a login page, there will be a sign-out button
on each activity
.
On clicking sign-out, I will be passing the session id
of the signed in user to sign-out. Can anyone guide me on how to keep session id
available to all activities
?
Any alternative to this case
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 s = getIntent().getStringExtra("EXTRA_SESSION_ID");
The docs for Intents has more information (look at the section titled "Extras").
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.
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.
链接地址: http://www.djcxy.com/p/4454.html