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 send data between activities using intent object. Consider you have two activities namely
FirstActivity
andSecondActivity
.Inside FirstActivity:
Using Intent:
Inside SecondActivity
Now you can use different bundle class methods to get values passed from FirstActivity by Key.
E.g.
bundle.getString("key")
,bundle.getDouble("key")
,bundle.getInt("key")
etc.You can use
Intent
Another way could be using singleton pattern also:
From your FirstActivity
On SecondActivity
Charlie Collins gave me a perfect answer using the
Application.class
. I was not aware that we could subclass it that easily. Here is a simplified example using a custom application class.AndroidManifest.xml
Give the
android:name
attribute to use your own application class.MyApplication.java
Use this as a global reference holder. It works fine within a same process.
MainActivity.java
Set the global "singleton" reference to the application instance.
MyPreferences.java
A simple example where I use a main activity from another activity instance.
The standard approach.
Now in your second activity retrieve your data from the bundle:
Get the bundle
Extract the data…
I recently released Vapor API, a jQuery flavored Android framework that makes all sorts of tasks like this simpler. As mentioned,
SharedPreferences
is one way you could do this.VaporSharedPreferences
is implemented as Singleton so that is one option, and in Vapor API it has a heavily overloaded.put(...)
method so you don't have to explicitly worry about the datatype you are committing - providing it is supported. It is also fluent, so you can chain calls:It also optionally autosaves changes, and unifies the reading and writing process under-the-hood so you don't need to explicitly retrieve an Editor like you do in standard Android.
Alternatively you could use an
Intent
. In Vapor API you can also use the chainable overloaded.put(...)
method on aVaporIntent
:And pass it as an extra, as mentioned in the other answers. You can retrieve extras from your
Activity
, and furthermore if you are usingVaporActivity
this is done for you automatically so you can use:To retrieve them at the other end in the
Activity
you switch to.Hope that is of interest to some :)
You can try Shared Preference, it may be a good alternative for sharing data between the activities
To save session id -
To get them -