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
Start another activity from this activity pass parameters via Bundle Object
Retrieve on another activity (YourActivity)
This is ok for simple kind data type. But if u want to pass complex data in between activity u need to serialize it first.
Here we have Employee Model
You can use Gson lib provided by google to serialize the complex data like this
You just have to send extras while calling your intent.
Like this:
Now on the
OnCreate
method of yourSecondActivity
you can fetch the extras like this.If the value you sent was in
long
:If the value you sent was a
String
:If the value you sent was a
Boolean
:I use static fields in a class, and get/set them:
Like:
For getting a value, use this in an Activity:
For setting a value:
In your current Activity, create a new
Intent
:Then in the new Activity, retrieve those values:
Use this technique to pass variables from one Activity to the other.
From Activity
To Activity
Here is my best practice and it helps a lot when the project is huge and complex.
Suppose that I have 2 activities,
LoginActivity
andHomeActivity
. I want to pass 2 parameters (username & password) fromLoginActivity
toHomeActivity
.First, I create my
HomeIntent
Here is how I pass the data in my LoginActivity
Final step, here is how I receive the data in
HomeActivity
Done! Cool :) I just want to share my experience. If you working on small project this shouldn't be the big problem. But when your working on big project, it really pain when you want to do refactoring or fixing bugs.