2010-01-19 06:06:36 8 Comments

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


@MurugananthamS 2019-04-08 09:09:43

We can pass the values to another Activity by two ways(same kind of answer already posted but redcing code here i posted which tried through intent)

1.through Intent

      startActivity(new Intent(getApplicationContext(),Activity2.class).putExtra("title","values"));

InActivity 2:

String recString= getIntent().getStringExtra("title");

2.Through SharedPreference


SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
 // 0 - for private mode
Editor editor = pref.edit();
editor.putString("key_name", "string value"); // Storing string
editor.commit(); // commit changes

   SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 

pref.getString("key_name", null); // getting String

@Rahul Sharma 2019-03-29 12:37:47

1st way:- In your current Activity, when you create object of intent to open new screen:

  String value="xyz";
  Intent intent = new Intent(CurrentActivity.this, NextActivity.class);    
  intent.putExtra("key", value);

Then in the nextActivity in onCreate method, retrieve those values which you pass from previous activity:

  if (getIntent().getExtras() != null) {
      String value = getIntent.getStringExtra("key");
      //The key argument must always match that used send and retrive value from one 
      activity to another.

2nd way:- You can create bundle object and put values in bundle and then put bundle object in intent from your current activity:-

  String value="xyz";
  Intent intent = new Intent(CurrentActivity.this, NextActivity.class);  
  Bundle bundle = new Bundle();
  bundle.putInt("key", value);  
  intent.putExtra("bundle_key", bundle);

Then in the nextActivity in onCreate method, retrieve those values which you pass from previous activity:

  if (getIntent().getExtras() != null) {
      Bundle bundle = getIntent().getStringExtra("bundle_key);    
      String value = bundle.getString("key");
      //The key argument must always match that used send and retrive value from one 
      activity to another.

You can also use bean class to pass data between classes using serialization.

@Mohsinali 2018-06-01 07:24:28

To do this in Java:

startActivity(new Intent(this, MainActivity.class).putExtra("userId", "2"));

@tdjprog 2019-01-12 04:16:40

New and real time interaction between activites using callbacks:

- STEP 01: Implement a shared interface

public interface SharedCallback {
    public String getSharedText(/*you can define arguments here*/);

- STEP 02: Implement a shared class

final class SharedMethode {
    private static Context mContext;

    private static SharedMethode sharedMethode = new SharedMethode();

    private SharedMethode() {

    public static SharedMethode getInstance() {
        return sharedMethode;

    public void setContext(Context context) {
        if (mContext != null)

        mContext = context;

    public boolean contextAssigned() {
        return mContext != null;

    public Context getContext() {
        return mContext;

    public void freeContext() {
        mContext = null;

- STEP 03 :: Play with code in First Activity

public class FirstActivity extends Activity implements SharedCallback {
    protected void onCreate(Bundle savedInstanceState) {

        // call playMe from here or there

    private void playMe() {
        Intent intent = new Intent(this, SecondActivity.class);

    public String getSharedText(/*passed arguments*/) {
        return "your result";


- STEP 04 :: Finalize the game in SecondActivity

public class SecondActivity extends Activity {

    private SharedCallback sharedCallback;

    protected void onCreate(Bundle savedInstanceState) {

        if (SharedMethode.getInstance().contextAssigned()) {
            if (SharedMethode.getInstance().getContext() instanceof SharedCallback)
                sharedCallback = (SharedCallback) SharedMethode.getInstance().getContext();

            // to prevent memory leak

        // You can now call your implemented methodes from anywhere at any time
        if (sharedCallback != null)
            Log.d("TAG", "Callback result = " + sharedCallback.getSharedText());


    protected void onDestroy() {
        sharedCallback = null;

  • STEP 05 :: you can also implement a backword callback (from First to Second) to get some results from SecondAvtivity or call some methods

@Khemraj 2018-10-10 09:07:41


Pass from First Activity

val intent = Intent(this,
intent.putExtra("key", "value")

Get in Second Activity

val value = getIntent().getStringExtra("key")


Always put keys in constant file for more managed way.

companion object {
    val KEY = "key"

@Khushboo Aggarwal 2018-09-21 12:34:38

you can communicate between two activities through intent. Whenever you are navigating to any other activity through your login activity, you can put your sessionId into intent and get that in other activities though getIntent(). Following is the code snippet for that :


Intent intent = new 


In onCreate() or wherever you need it call getIntent().getStringExtra("SESSION_ID"); Also make sure to check for if the intent is null and key you are passing in the intent should be same in both activities. Here is the full code snippet:

        if(getIntent!=null && getIntent.getStringExtra("SESSION_ID")!=null){
          sessionId = getIntent.getStringExtra("SESSION_ID");

However, I would suggest you to use AppSharedPreferences to store your sessionId and get it from that wherever needed.

@Vincent Mungai 2018-09-17 23:19:04

In the Destination activity define like this

public class DestinationActivity extends AppCompatActivity{

    public static Model model;
    public static void open(final Context ctx, Model model){
          DestinationActivity.model = model;
          ctx.startActivity(new Intent(ctx, DestinationActivity.class))

    public void onCreate(/*Parameters*/){
           //Use model here

In the first activity, start the second activity like below,model);

@Nitish 2018-08-30 11:25:28

You can use intent class to send data between Activities. It is basically a message to OS where you describe source and destination of data flow. Like data from A to B activity.

In ACTIVITY A (the source):

Intent intent = new Intent(A.this, B.class);



In Activity B (the destination)->

Intent intent =getIntent();

String data =intent.getString("KEY");

Here you will get data for key "KEY"


Like this:

public class Constants{
public static String KEY="KEY"



In Activity B:

String data =intent.getString(Constants.KEY);

@Erich Douglass 2010-01-19 06:12:08

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);

Access that intent on next activity

String sessionId= getIntent().getStringExtra("EXTRA_SESSION_ID");

The docs for Intents has more information (look at the section titled "Extras").

@UMAR 2010-01-19 06:57:10

ok if i pass session id to signout acitivity on successful login and will it work on any activity page to signout or manually i will have to assign it value on each activity??? using above procedure??

@Erich Douglass 2010-01-19 15:16:30

Yes, you'd have to make the session ID available to every activity where you want to allow the user to signout. Alternatively, you could store it in the Application object, but then you'd have to manage the state of the session (check if it's valid before using, etc).

@Leander 2013-04-16 07:50:13

That is only half an answer! Now how to read the extra info in the new Activity?

@Warren Sergent 2013-05-10 21:42:22

Leander - see user914425's answer below for more complete response.

@wutzebaer 2013-07-27 17:29:06

does this work if the target activity already runs in background? my onresume function olds alwas just the first intend

@Serguei Fedorov 2013-11-13 16:25:27

Please be aware that the documentation points the following: Add extended data to the intent. The name must include a package prefix, for example the app would use names like "".

@beplaya 2014-04-24 14:16:56

Use Wagon. It makes it simpler:

@FARID 2016-04-09 18:39:43

And to read data from other Activity use Long session_ids=getIntent().getExtras().getLong("EXTRA_SESSION_I‌​DS");

@H. Aqjn 2016-07-18 13:04:10

How can we pass data using setData and what is difference between theses two approaches? Which one is better?

@matrix 2018-02-27 15:39:34

Take a look at this library for easy handling intent data:

@Ashish Kumar 2019-02-15 05:42:35

we can send data with multiple way like 1- Intent

@Shivam Yadav 2019-03-11 11:44:03

Be aware of TransactionTooLargeException , if your data exceeds 1 mb size then it will throw exception. So take care while sending complete list.

@suresh madaparthi 2018-07-23 07:11:26

First Activity:

Intent intent = new Intent(getApplicationContext(), ClassName.class);
intent.putExtra("Variable name", "Value you want to pass");

Second Activity:

String str= getIntent().getStringExtra("Variable name which you sent as an extra");

@Sachin 2016-11-28 06:38:26

You can use Intent

Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
mIntent.putExtra("data", data);

Another way could be using singleton pattern also:

public class DataHolder {

 private static DataHolder dataHolder;
 private List<Model> dataList;

 public void setDataList(List<Model>dataList) {
    this.dataList = dataList;

 public List<Model> getDataList() {
    return dataList;

 public synchronized static DataHolder getInstance() {
    if (dataHolder == null) {
       dataHolder = new DataHolder();
    return dataHolder;

From your FirstActivity

private List<Model> dataList = new ArrayList<>();

On SecondActivity

private List<Model> dataList = DataHolder.getInstance().getDataList();

@Murmel 2017-11-22 01:01:51

Duplicate: The intent approach is already proposed by the top most voted answer and of Sahil Mahajan Mj's answer and of Mayank Saini's answer and Md. Rahman's answer, Dilavar M's answer, android developer's answer, sahulab. Singleton: Rodion Altshuler answer

@Lavanya Velusamy 2018-05-07 06:45:14

You can pass data between activities in application in 3 ways 1.Intent 2.SharedPreferences 3.Application

passing data in intent have some limit.For large amount of data you can use Application level data sharing and by storing it in sharedpref makes your app size increase

@user5876477 2018-04-29 11:37:45

Your data object should extend Parcelable or Serializable class

Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
mIntent.putExtra("data", data);

@THANN Phearum 2016-08-08 02:49:08

Here is my best practice and it helps a lot when the project is huge and complex.

Suppose that I have 2 activities, LoginActivity and HomeActivity. I want to pass 2 parameters (username & password) from LoginActivity to HomeActivity.

First, I create my HomeIntent

public class HomeIntent extends Intent {

    private static final String ACTION_LOGIN = "action_login";
    private static final String ACTION_LOGOUT = "action_logout";

    private static final String ARG_USERNAME = "arg_username";
    private static final String ARG_PASSWORD = "arg_password";

    public HomeIntent(Context ctx, boolean isLogIn) {
        //set action type
        setAction(isLogIn ? ACTION_LOGIN : ACTION_LOGOUT);

    public HomeIntent(Context ctx) {
        super(ctx, HomeActivity.class);

    //This will be needed for receiving data
    public HomeIntent(Intent intent) {

    public void setData(String userName, String password) {
        putExtra(ARG_USERNAME, userName);
        putExtra(ARG_PASSWORD, password);

    public String getUsername() {
        return getStringExtra(ARG_USERNAME);

    public String getPassword() {
        return getStringExtra(ARG_PASSWORD);

    //To separate the params is for which action, we should create action
    public boolean isActionLogIn() {
        return getAction().equals(ACTION_LOGIN);

    public boolean isActionLogOut() {
        return getAction().equals(ACTION_LOGOUT);

Here is how I pass the data in my LoginActivity

public class LoginActivity extends AppCompatActivity {
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        String username = "phearum";
        String password = "pwd1133";
        final boolean isActionLogin = true;
        //Passing data to HomeActivity
        final HomeIntent homeIntent = new HomeIntent(this, isActionLogin);
        homeIntent.setData(username, password);


Final step, here is how I receive the data in HomeActivity

public class HomeActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {

        //This is how we receive the data from LoginActivity
        //Make sure you pass getIntent() to the HomeIntent constructor
        final HomeIntent homeIntent = new HomeIntent(getIntent());
        Log.d("HomeActivity", "Is action login?  " + homeIntent.isActionLogIn());
        Log.d("HomeActivity", "username: " + homeIntent.getUsername());
        Log.d("HomeActivity", "password: " + homeIntent.getPassword());

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.

@Darius 2013-02-26 11:49:37

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:

$.prefs(...).put("val1", 123).put("val2", "Hello World!").put("something", 3.34);

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 a VaporIntent:

$.Intent().put("data", "myData").put("more", 568)...

And pass it as an extra, as mentioned in the other answers. You can retrieve extras from your Activity, and furthermore if you are using VaporActivity 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 :)

@Banee Ishaque K 2018-01-23 18:59:33

The URL is unreachable...

@Darius 2018-04-02 09:30:52

@BaneeIshaqueK yep sorry, haven't maintained this for a while. Have updated link to point directly to the Github for the project in case it helps. ps. Not sure what I was thinking for that license... apologies

@user914425 2011-09-06 19:41:23

In your current Activity, create a new Intent:

String value="Hello world";
Intent i = new Intent(CurrentActivity.this, NewActivity.class);    

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.

@bish 2013-08-16 16:13:16

Just an info for those who are so blind like me: if you put an integer in your current activity, you have to get it in the new one via extras.getInt("new_variable_name"). If you try to get it via getString() android see's that a int was given and returns null!

@beplaya 2014-04-24 14:16:32

Use Wagon. It makes it simpler:

@Francisco Corrales Morales 2014-05-08 23:25:40

what if the activity is already running, is there need to do startActivity(i); ? I mean, can I make activity A call activity B, and that returns data to activity A ? am I confused ?

@drorw 2014-07-30 21:31:03

@user914425 2015-04-25 16:54:58

I prefer string variable. You can always convert a string to integer or float later.

@Whome 2013-12-14 15:22:44

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.


Give the android:name attribute to use your own application class.

<application android:name="MyApplication"
    android:theme="@style/AppTheme" >

Use this as a global reference holder. It works fine within a same process.

public class MyApplication extends Application {
    private MainActivity mainActivity;

    public void onCreate() {

    public void setMainActivity(MainActivity activity) { this.mainActivity=activity; }
    public MainActivity getMainActivity() { return mainActivity; }

Set the global "singleton" reference to the application instance.

public class MainActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {


A simple example where I use a main activity from another activity instance.

public class MyPreferences extends PreferenceActivity
            implements SharedPreferences.OnSharedPreferenceChangeListener {
    public void onCreate(Bundle savedInstanceState) {

    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
        if (!key.equals("autostart")) {

@Gavine Joyce 2016-06-23 01:44:07

From Activity

 int n= 10;
 Intent in = new Intent(From_Activity.this,To_Activity.class);
 Bundle b1 = new Bundle();

To Activity

 Bundle b2 = getIntent().getExtras();
 int m = 0;
 if(b2 != null)
     m = b2.getInt("integerNumber");

@Murmel 2017-11-22 00:52:02

Duplicate: The Bundle based approach was already proposed by PRABEESH R K in 2012 and Ajay Venugopal, Krishna. And could be reduced to the i.putExtras()/getIntent().getString() which is proposed by 8 other answers...

@Suragch 2017-08-31 10:35:53

It helps me to see things in context. Here are two examples.

Passing Data Forward

enter image description here

Main Activity

  • Put the data you want to send in an Intent with a key-value pair. See this answer for naming conventions for the key.
  • Start the Second Activity with startActivity.

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {

    // "Go to Second Activity" button click
    public void onButtonClick(View view) {

        // get the text to pass
        EditText editText = (EditText) findViewById(;
        String textToPass = editText.getText().toString();

        // start the SecondActivity
        Intent intent = new Intent(this, SecondActivity.class);
        intent.putExtra(Intent.EXTRA_TEXT, textToPass);

Second Activity

  • You use getIntent() to get the Intent that started the second activity. Then you can extract the data with getExtras() and the key you defined in the first activity. Since our data is a String we will just use getStringExtra here.

public class SecondActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {

        // get the text from MainActivity
        Intent intent = getIntent();
        String text = intent.getStringExtra(Intent.EXTRA_TEXT);

        // use the text in a TextView
        TextView textView = (TextView) findViewById(;

Passing Data Back

enter image description here

Main Activity

  • Start the Second Activity with startActivityForResult, providing it an arbitrary result code.
  • Override 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.)
  • Extract the data you got from the return Intent. The data is extracted using a key-value pair. I could use any string for the key but I'll use the predefined Intent.EXTRA_TEXT since I'm sending text.

public class MainActivity extends AppCompatActivity {

    private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;

    protected void onCreate(Bundle savedInstanceState) {

    // "Go to Second Activity" button click
    public void onButtonClick(View view) {

        // Start the SecondActivity
        Intent intent = new Intent(this, SecondActivity.class);
        startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);

    // This method is called when the second activity finishes
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // check that it is the SecondActivity with an OK result
        if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                // get String data from Intent
                String returnString = data.getStringExtra(Intent.EXTRA_TEXT);

                // set text view with string
                TextView textView = (TextView) findViewById(;

Second Activity

  • Put the data that you want to send back to the previous activity into an Intent. The data is stored in the Intent using a key-value pair. I chose to use Intent.EXTRA_TEXT for my key.
  • Set the result to RESULT_OK and add the intent holding your data.
  • Call finish() to close the Second Activity.

public class SecondActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {

    // "Send text back" button click
    public void onButtonClick(View view) {

        // get the text from the EditText
        EditText editText = (EditText) findViewById(;
        String stringToPassBack = editText.getText().toString();

        // put the String to pass back into an Intent and close this activity
        Intent intent = new Intent();
        intent.putExtra(Intent.EXTRA_TEXT, stringToPassBack);
        setResult(RESULT_OK, intent);

@user3195231 2018-07-11 13:55:53

Wow, thank you! This was quite what I was looking for. It is quite clear when using camera or other externals that I expect results back, but I didn't think to use it internally. You're the first to put it quite so openly.

@angryITguy 2011-02-17 03:06:45

Updated Note that I had mentioned the use of SharedPreference. It has a simple API and is accessible across an application's activities. But this is a clumsy solution, and is a security risk if you pass around sensitive data. It's best to use intents. It has an extensive list of overloaded methods that can be used to better transfer many different data types between activities. Have a look at intent.putExtra. This link presents the use of putExtra quite well.

In passing data between activities, my preferred approach is to create a static method for the relevant activity that includes the required parameters launch the intent. Which then provides easily setup and retrieve parameters. So it can look like this

public class MyActivity extends Activity {
    public static final String ARG_PARAM1 = "arg_param1";
public static getIntent(Activity from, String param1, Long param2...) {
    Intent intent = new Intent(from, MyActivity.class);
        intent.putExtra(ARG_PARAM1, param1);
        intent.putExtra(ARG_PARAM2, param2);
        return intent;

// Use it like this.
startActivity(MyActvitiy.getIntent(FromActivity.this, varA, varB, ...));

Then you can create an intent for the intended activity and ensure you have all the parameters. You can adapt for fragments to. A simple example above, but you get the idea.

@bytebender 2012-02-28 01:06:14

I like your answer best... Passing it via the intent means that almost everywhere I start an activity you will have to remember to include the sessionId. By putting it in the SharedPreferences you can get it anytime from any activity. :0)

@Rodion Altshuler 2013-12-09 14:51:38

Consider using a singleton to hold your session information accessible to all the Activities.

This approach has several advantages compared to extras and static variables:

  1. Allows you to extend Info class, adding new user information settings you need. You could make a new class inheriting it or just edit the Info class without the need to change extras handling in all the places.
  2. Easy usage - no need to get extras in every activity.

    public class Info {
        private static Info instance;
        private int id;
        private String name;
        //Private constructor is to disallow instances creation outside create() or getInstance() methods
        private Info() {
        //Method you use to get the same information from any Activity.
        //It returns the existing Info instance, or null if not created yet.
        public static Info getInstance() {
            return instance;
        //Creates a new Info instance or returns the existing one if it exists.
        public static synchronized Info create(int id, String name) {
            if (null == instance) {
                instance = new Info();
       = id;
       = name;
            return instance;

@DroidNinja 2017-06-23 11:56:11

Start another activity from this activity pass parameters via Bundle Object

Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "[email protected]");

Retrieve on another activity (YourActivity)

String s = getIntent().getStringExtra("USER_NAME");

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

class Employee{
    private String empId;
    private int age;
    print Double salary;


You can use Gson lib provided by google to serialize the complex data like this

String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);

Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
            Gson gson = new Gson();
            Type type = new TypeToken<Employee>() {
            Employee selectedEmp = gson.fromJson(empStr, type);

@Ali hasan 2017-07-04 16:26:53

If you use kotlin:

In MainActivity1:

var intent=Intent(this,

In MainActivity2:

if (intent.hasExtra("EXTRA_SESSION_ID")){
    var name:String=intent.extras.getString("sessionId")

@MageNative 2017-05-19 05:05:09

For Using the session id in all the activities you can follow the following steps.

1-Define one STATIC VARIABLE session( which will hold the value of session id ) in the APPLICATION file of your app.

2-Now call the session variable with the class reference where you are fetching the session id value and assign it to static variable.

3-Now you can use this session id value anywhere by just calling the static variable by the

@Murmel 2017-11-22 01:13:56

Duplicate: the static approach was already proposed by ComputerSaysNo and Przemek and javadaskari and Mohamed Selim

@Android Player _Shree 2017-05-10 06:37:04

Write following code in

Intent i = new Intent(CurrentActivity.this, SignOutActivity.class);

Access SessionId in is following way

public void onCreate(Bundle savedInstanceState){
    Intent intent = getIntent();

    // check intent is null or not
    if(intent != null){
        String sessionId = i.getStringExtra("SESSION_ID");
        Log.d("Session_id : " + sessionId);
        Toast.makeText(SignOutActivity.this, "Intent is null", Toast.LENGTH_SHORT).show();

@Murmel 2017-11-22 01:11:35

@Rohit Gurjar 2017-05-04 11:49:26

You can try Shared Preference, it may be a good alternative for sharing data between the activities

To save session id -

SharedPreferences pref = myContexy.getSharedPreferences("Session 
SharedPreferences.Editor edit = pref.edit();
edit.putInt("Session ID", session_id);

To get them -

SharedPreferences pref = myContexy.getSharedPreferences("Session Data", MODE_PRIVATE);
session_id = pref.getInt("Session ID", 0);

@Murmel 2017-11-22 01:06:07

Duplicate: This approach was already propsed by Ravi Parsania in 2014

@MurugananthamS 2016-09-01 06:13:24

Try this:

Intent intent = new Intent(currentActivity.this, TargetActivity.class);
intent.putExtra("booktype", "favourate");

Bundle b = getIntent().getExtras();
String typesofbook = b.getString("booktype");

@Murmel 2017-11-22 00:55:24

Duplicate: The Bundle based approach was already proposed by PRABEESH R K in 2012 and Ajay Venugopal, Krishna, Gavine Joyce. And could be reduced to the i.putExtras()/getIntent().getString() which is proposed by 7 other answers...

@ponkin 2010-01-19 07:16:53

Try to do the following:

Create a simple "helper" class (factory for your Intents), like this:

import android.content.Intent;

public class IntentHelper {
    public static final Intent createYourSpecialIntent(Intent src) {
          return new Intent("YourSpecialIntent").addCategory("YourSpecialCategory").putExtras(src);

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:

IntentHelper.createYourSpecialIntent(getIntent()).putExtra("YOUR_FIELD_NAME", fieldValueToSave);

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).

@Vaibhav Sharma 2016-02-15 09:58:16

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 Click on build and you will get new code. Copy all of this and replace the original class contents. Then-

Intent intent = new Intent(getBaseContext(), NextActivity.class);
Foo foo = new Foo();
intent.putExtra("foo", foo);

and get the result in NextActivity like-

Foo foo = getIntent().getExtras().getParcelable("foo");

Now you can simply use the foo object like you would have used.

@Suragch 2016-11-13 00:18:27

Supplemental Answer: Naming Conventions for the Key String

The actual process of passing data has already been answered, however most of the answers use hard coded strings for the key name in the Intent. This is usually fine when used only within your app. However, the documentation recommends using the EXTRA_* constants for standardized data types.

Example 1: Using Intent.EXTRA_* keys

First activity

Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, "my text");

Second activity:

Intent intent = getIntent();
String myText = intent.getExtras().getString(Intent.EXTRA_TEXT);

Example 2: Defining your own static final key

If one of the Intent.EXTRA_* Strings does not suit your needs, you can define your own at the beginning of the first activity.

static final String EXTRA_STUFF = "com.myPackageName.EXTRA_STUFF";

Including the package name is just a convention if you are only using the key in your own app. But it is a necessity to avoid naming conflicts if you are creating some sort of service that other apps can call with an Intent.

First activity:

Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(EXTRA_STUFF, "my text");

Second activity:

Intent intent = getIntent();
String myText = intent.getExtras().getString(FirstActivity.EXTRA_STUFF);

Example 3: Using a String resource key

Although not mentioned in the documentation, this answer recommends using a String resource to avoid dependencies between activities.


 <string name="EXTRA_STUFF">com.myPackageName.MY_NAME</string>

First activity

Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(getString(R.string.EXTRA_STUFF), "my text");

Second activity

Intent intent = getIntent();
String myText = intent.getExtras().getString(getString(R.string.EXTRA_STUFF));

Related Questions

Sponsored Content

34 Answered Questions

31 Answered Questions

27 Answered Questions

42 Answered Questions

8 Answered Questions

77 Answered Questions

31 Answered Questions

[SOLVED] Activity restart on rotation Android

19 Answered Questions

[SOLVED] How do I create a transparent Activity on Android?

31 Answered Questions

18 Answered Questions

[SOLVED] Fling gesture detection on grid layout

Sponsored Content