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 most convenient way to pass data between activities is by passing intents. In the first activity from where you want to send data, you should add code,
You should also import
Then in the next Acitvity(SecondActivity), you should retrieve the data from the intent using the following code.
Another way is to use a public static field in which you store data, i.e.:
Use a global class:
You can call the setters and the getters of this class from all other classes. Do do that, you need to make a GlobalClass-Object in every Actitity:
Then you can call for example:
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.
Try to do the following:
Create a simple "helper" class (factory for your Intents), like this:
This will be the factory for all your Intents. Everytime you need a new Intent, create a static factory method in IntentHelper. To create a new Intent you should just say it like this:
In your activity. When you want to "save" some data in a "session" just use the following:
And send this Intent. In the target Activity your field will be available as:
So now we can use Intent like same old session (like in servlets or JSP).