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
You can retrieve it in another activity. Two ways:
The second way is:
Kotlin
Pass from First Activity
Get in Second Activity
Suggestion
Always put keys in constant file for more managed way.
It helps me to see things in context. Here are two examples.
Passing Data Forward
Main Activity
startActivity
.MainActivity.java
Second Activity
getIntent()
to get theIntent
that started the second activity. Then you can extract the data withgetExtras()
and the key you defined in the first activity. Since our data is a String we will just usegetStringExtra
here.SecondActivity.java
Passing Data Back
Main Activity
startActivityForResult
, providing it an arbitrary result code.onActivityResult
. This is called when the Second Activity finishes. You can make sure that it is actually the Second Activity by checking the result code. (This is useful when you are starting multiple different activities from the same main activity.)Intent
. The data is extracted using a key-value pair. I could use any string for the key but I'll use the predefinedIntent.EXTRA_TEXT
since I'm sending text.MainActivity.java
Second Activity
Intent
. The data is stored in theIntent
using a key-value pair. I chose to useIntent.EXTRA_TEXT
for my key.RESULT_OK
and add the intent holding your data.finish()
to close the Second Activity.SecondActivity.java
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:Access that intent on next activity:
The docs for Intents has more information (look at the section titled "Extras").
Source class:
Destination Class (NewActivity class):
You can also pass custom class objects by making a parcelable class. Best way to make it parcelable is to write your class and then simply paste it to a site like http://www.parcelabler.com/. Click on build and you will get new code. Copy all of this and replace the original class contents. Then-
and get the result in NextActivity like-
Now you can simply use the foo object like you would have used.