1424

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

Sachin
  • 3,815
  • 2
  • 13
  • 26
UMAR-MOBITSOLUTIONS
  • 73,009
  • 94
  • 197
  • 273
  • 17
    i used sharedpreference its useful also to keep login data on remeber password feature – shareef Dec 02 '12 at 19:33
  • This works for me. http://stackoverflow.com/a/7325248/2125322 Thanks Darshan Computing – matasoy Sep 01 '13 at 20:59
  • http://stackoverflow.com/a/37774966/6456129 may be helpful – Yessy Jul 24 '16 at 05:48
  • for such cases try making commomUtils class with sharedprefereces Method... this will keep the code clean and related data at a place . And you will easily be able to Clear specific set of data with just one method of clearing that specific prefrencesFile,without clearing any of default app data... – Muahmmad Tayyib Jan 08 '19 at 12:52

52 Answers52

1429

In your current Activity, create a new Intent:

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

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.

ADM
  • 16,256
  • 11
  • 37
  • 69
user914425
  • 15,321
  • 4
  • 25
  • 39
  • 64
    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! – bish Aug 16 '13 at 16:13
  • 5
    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 ? – Francisco Corrales Morales May 08 '14 at 23:25
  • 3
    Here's a [nice example that sets and retrieves intent extras](http://www.codota.com/android/scenarios/52fcbcffda0ace249b7bce8e/android.content.Intent?tag=dragonfly) – drorw Jul 30 '14 at 21:31
  • 1
    I prefer string variable. You can always convert a string to integer or float later. – user914425 Apr 25 '15 at 16:54
1393

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);
startActivity(intent);

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

Jens Piegsa
  • 6,630
  • 5
  • 47
  • 95
Erich Douglass
  • 49,906
  • 11
  • 72
  • 60
  • 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?? – UMAR-MOBITSOLUTIONS Jan 19 '10 at 06:57
  • 6
    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). – Erich Douglass Jan 19 '10 at 15:16
  • does this work if the target activity already runs in background? my onresume function olds alwas just the first intend – wutzebaer Jul 27 '13 at 17:29
  • 1
    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 com.android.contacts would use names like "com.android.contacts.ShowAll". – Serguei Fedorov Nov 13 '13 at 16:25
  • Use Wagon. It makes it simpler: github.com/beplaya/Wagon – beplaya Apr 24 '14 at 14:16
  • 1
    And to read data from other Activity use `Long session_ids=getIntent().getExtras().getLong("EXTRA_SESSION_IDS");` – Farid Apr 09 '16 at 18:39
  • 1
    How can we pass data using `setData` and what is difference between theses two approaches? Which one is better? – Hosein Aqajani Jul 18 '16 at 13:04
  • Take a look at this library for easy handling intent data: https://github.com/kostasdrakonakis/android_navigator – matrix Feb 27 '18 at 15:39
  • we can send data with multiple way like 1- Intent – Ashish Kumar Feb 15 '19 at 05:42
  • Be aware of TransactionTooLargeException , if your data exceeds 1 mb size then it will throw exception. So take care while sending complete list. – Shivam Yadav Mar 11 '19 at 11:44
147

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.

Jeremy Logan
  • 45,614
  • 37
  • 119
  • 143
Charlie Collins
  • 8,506
  • 4
  • 29
  • 41
  • 8
    +1 for the statics problem. probably the clean up can be resolved by combining a singleton with onCreate/onTerminate method Application class. – Syd Nov 17 '10 at 22:33
  • 12
    Hey, I know this thread was quite a while back, but the link provided is now a dead end. Is there anywhere I can find the example? – JuiCe Jun 15 '12 at 14:38
  • How to achieve this using Application? @CharlieCollins – Banee Ishaque K Jan 23 '18 at 18:44
  • Here's an updated example of this here, from a very old book :) https://github.com/charlieCollins/android-in-practice/blob/master/ch07/MyMoviesDatabase/src/com/manning/aip/mymoviesdatabase/MyMovies.java – Charlie Collins Jan 29 '18 at 22:01
  • @JuiCe The Android Developers blog post on memory leaks is no longer invalid. – Edric Mar 29 '20 at 15:56
99

Source class:

Intent myIntent = new Intent(this, NewActivity.class);
myIntent.putExtra("firstName", "Your First Name Here");
myIntent.putExtra("lastName", "Your Last Name Here");
startActivity(myIntent)

Destination Class (NewActivity class):

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view);

    Intent intent = getIntent();

    String fName = intent.getStringExtra("firstName");
    String lName = intent.getStringExtra("lastName");
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Md. Rahman
  • 1,682
  • 12
  • 15
  • 3
    Can the intent ever be null? Should we check that it is not null? – Micro Mar 06 '16 at 20:24
  • This is a duplicate of the 3 years older [top most voted answer](https://stackoverflow.com/a/7325248/1885518) and of [Sahil Mahajan Mj's answer](https://stackoverflow.com/a/12137344/1885518) and of [Mayank Saini's answer](https://stackoverflow.com/a/16733899/1885518) – Murmel Nov 22 '17 at 00:11
88

You just have to send extras while calling your intent.

Like this:

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

Now on the OnCreate method of your SecondActivity you can fetch the extras like this.

If the value you sent was in long:

long value = getIntent().getLongExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));

If the value you sent was a String:

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

If the value you sent was a Boolean:

Boolean value = getIntent().getBooleanExtra("Variable name which you sent as an extra", defaultValue);
Vasily Kabunov
  • 5,179
  • 12
  • 41
  • 46
Mayank Saini
  • 2,957
  • 22
  • 25
  • 3
    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 com.android.contacts would use names like "com.android.contacts.ShowAll". – Serguei Fedorov Nov 13 '13 at 16:23
  • This is a duplicate of the top most voted answer which has been there for 2 years before this answer and of [Sahil Mahajan Mj's answer](https://stackoverflow.com/a/12137344/1885518) which is 1 year older. Only difference: examples for `boolean` and `long` getters which is worth a comment IMO, not an answer. – Murmel Nov 21 '17 at 23:50
56

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.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

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

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

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

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.

SecondActivity.java

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        // 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(R.id.textView);
        textView.setText(text);
    }
}

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.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // "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
    @Override
    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(R.id.textView);
                textView.setText(returnString);
            }
        }
    }
}

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.

SecondActivity.java

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }

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

        // get the text from the EditText
        EditText editText = (EditText) findViewById(R.id.editText);
        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);
        finish();
    }
}
Suragch
  • 364,799
  • 232
  • 1,155
  • 1,198
  • 3
    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. – user3195231 Jul 11 '18 at 13:55
48

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.

angryITguy
  • 8,747
  • 8
  • 51
  • 79
  • 2
    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) – bytebender Feb 28 '12 at 01:06
  • @bytebender I know this is a bit late for the response, I appreciate that you like my original answer for its simlpicity, but I would be careful to storing session ID in shared preferences. If you must store it on hard storage then use encryption. If you can use an authentication frameworks that employs JWT, it will include refreshTokens which are safer for long term storage, and then keep the current session token as a public property of a custom Application object to easily access authentication tokens, and reduce overhead on activity intent signatures. – angryITguy May 27 '19 at 00:57
41

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:

IntentHelper.createYourSpecialIntent(getIntent());

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:

getIntent().getStringExtra("YOUR_FIELD_NAME");

So now we can use Intent like same old session (like in servlets or JSP).

ponkin
  • 2,181
  • 17
  • 24
31

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-

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

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.

Vaibhav Sharma
  • 2,113
  • 1
  • 15
  • 21
24

Another way is to use a public static field in which you store data, i.e.:

public class MyActivity extends Activity {

  public static String SharedString;
  public static SomeObject SharedObject;

//...
  • 5
    I really wonder why your suggestion did't get votes, it's simpler and more practical. – Porizm Nov 15 '12 at 18:58
  • @FirasMoussa thank you, I just added this recently, the original question was asked 2 years ago, maybe there were some limitations back then, I've added mine because it seems much more simpler and could help others that are just starting on android. –  Nov 15 '12 at 23:14
  • 7
    um... doesn't this violates OO principles? – Christian Vielma Aug 06 '13 at 22:05
  • 2
    @ChristianVielma well, it's more like a gray area... you can do it many ways, to me it seems like a clean "get away", so... it's up to you(the developer) to make the decision if it works good for you or not, I like this way because it's easier to follow, but it can get very dirty very fast... –  Aug 07 '13 at 08:37
  • 2
    why do you say this gets dirty? Doesn't iOS do this to pass data between viewcontrollers by setting "properties" which is similar to this? This is so much easier than using intents – Terry Bu Nov 01 '14 at 20:40
  • 2
    Yes, you pass data between view controllers, but not with *static* properties. The problem is it's not a property on the desired activity instance. The way Android launches activities via startActivity(), it doesn't instantly instantiate the object and allow the developer to set an instance variable. It's pretty annoying... – Shawn Apr 07 '16 at 20:49
  • 2
    In case two of these Activities are launched, which is not an unlikely scenario if your app is not singleTask or singleInstance, the static variables will be shared between those activities leading to potential bugs. Also what happens when you navigate from A activity which has static Objects to B activity and A activity gets destroyed due to low memory? – z3n105 Sep 02 '16 at 13:51
  • 1
    Oh lord, this just hurts my eyes. Please look at the accepted answer if you wanna do it correctly – finki Oct 02 '18 at 12:17
  • Well I learned the consequences of this approach in the hard way. This approach will definetely throw null pointer exceptions if the Activity A get killed by the system before Activity B is launched (Assume Activity B is the consumer of the static object). This is not theoritical, it could happen anytime. Please try to follow better programming practices. – Amila Abeygunasekara Jun 13 '20 at 17:44
22

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,

String str = "My Data"; //Data you want to send
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("name",str); //Here you will add the data into intent to pass bw activites
v.getContext().startActivity(intent);

You should also import

import android.content.Intent;

Then in the next Acitvity(SecondActivity), you should retrieve the data from the intent using the following code.

String name = this.getIntent().getStringExtra("name");
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Sahil Mahajan Mj
  • 12,525
  • 8
  • 53
  • 98
  • 2
    This is a duplicate of the [top most voted answer](https://stackoverflow.com/a/7325248/1885518) which has been there for even 1 year more. – Murmel Nov 21 '17 at 23:23
21

You can use SharedPreferences...

  1. Logging. Time store session id in SharedPreferences

    SharedPreferences preferences = getSharedPreferences("session",getApplicationContext().MODE_PRIVATE);
    Editor editor = preferences.edit();
    editor.putString("sessionId", sessionId);
    editor.commit();
    
  2. Signout. Time fetch session id in sharedpreferences

    SharedPreferences preferences = getSharedPreferences("session", getApplicationContext().MODE_PRIVATE);
    String sessionId = preferences.getString("sessionId", null);
    

If you don't have the required session id, then remove sharedpreferences:

SharedPreferences settings = context.getSharedPreferences("session", Context.MODE_PRIVATE);
settings.edit().clear().commit();

That is very useful, because one time you save the value and then retrieve anywhere of activity.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Ravi Parsania
  • 675
  • 6
  • 10
19

The standard approach.

Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
Bundle bundle = new Bundle();
bundle.putString(“stuff”, getrec);
i.putExtras(bundle);
startActivity(i);

Now in your second activity retrieve your data from the bundle:

Get the bundle

Bundle bundle = getIntent().getExtras();

Extract the data…

String stuff = bundle.getString(“stuff”); 
Ajay Venugopal
  • 1,209
  • 15
  • 28
  • 1
    Duplicate as already proposed by [PRABEESH R K](https://stackoverflow.com/a/13100481/1885518) in 2012. And could be reduced to the `i.putExtras()`/`getIntent().getString()` which is proposed by 6 other answers... – Murmel Nov 22 '17 at 00:32
19

From Activity

 int n= 10;
 Intent in = new Intent(From_Activity.this,To_Activity.class);
 Bundle b1 = new Bundle();
 b1.putInt("integerNumber",n);
 in.putExtras(b1);
 startActivity(in);

To Activity

 Bundle b2 = getIntent().getExtras();
 int m = 0;
 if(b2 != null)
  {
     m = b2.getInt("integerNumber");
  }
demo
  • 582
  • 3
  • 7
  • 31
Gavine Joyce
  • 351
  • 3
  • 8
12

You can send data between activities using intent object. Consider you have two activities namely FirstActivity and SecondActivity.

Inside FirstActivity:

Using Intent:

i = new Intent(FirstActivity.this,SecondActivity.class);
i.putExtra("key", value);
startActivity(i)

Inside SecondActivity

Bundle bundle= getIntent().getExtras();

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.

Raceimaztion
  • 8,844
  • 4
  • 24
  • 38
Krishna
  • 2,103
  • 14
  • 22
  • 1
    Duplicate: The `Bundle` based approach was already proposed by [PRABEESH R K](https://stackoverflow.com/a/13100481/1885518) in 2012 and [Ajay Venugopal](https://stackoverflow.com/a/28192658/1885518). And could be reduced to the `i.putExtras()`/`getIntent().getString()` which is proposed by 7 other answers... – Murmel Nov 22 '17 at 00:43
12

If you want to tranfer bitmap between Activites/Fragments


Activity

To pass a bitmap between Activites

Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);

And in the Activity class

Bitmap bitmap = getIntent().getParcelableExtra("bitmap");

Fragment

To pass a bitmap between Fragments

SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);

To receive inside the SecondFragment

Bitmap bitmap = getArguments().getParcelable("bitmap");

Transfering Large Bitmaps

If you are getting failed binder transaction, this means you are exceeding the binder transaction buffer by transferring large element from one activity to another activity.

So in that case you have to compress the bitmap as an byte's array and then uncompress it in another activity, like this

In the FirstActivity

Intent intent = new Intent(this, SecondActivity.class);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray(); 
intent.putExtra("bitmapbytes",bytes);

And in the SecondActivity

byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
capt.swag
  • 8,997
  • 1
  • 33
  • 35
10
Intent intent = new Intent(YourCurrentActivity.this, YourActivityName.class);
intent.putExtra("NAme","John");
intent.putExtra("Id",1);
startActivity(intent);

You can retrieve it in another activity. Two ways:

int id = getIntent.getIntExtra("id", /* defaltvalue */ 2);

The second way is:

Intent i = getIntent();
String name = i.getStringExtra("name");
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Dilavar Malek
  • 1,099
  • 11
  • 17
  • This is a duplicate of the 3 years older [top most voted answer](https://stackoverflow.com/a/7325248/1885518) and of [Sahil Mahajan Mj's answer](https://stackoverflow.com/a/12137344/1885518) and of [Mayank Saini's answer](https://stackoverflow.com/a/16733899/1885518) and [Md. Rahman's answer](https://stackoverflow.com/a/21602897/1885518) – Murmel Nov 22 '17 at 00:14
9

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) {
        this(ctx);
        //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) {
        super(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 {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        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);
        startActivity(homeIntent);

    }
}

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

public class HomeActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

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

THANN Phearum
  • 1,609
  • 20
  • 16
8

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");
startActivity(intent);

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");
startActivity(intent);

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.

strings.xml

 <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");
startActivity(intent);

Second activity

Intent intent = getIntent();
String myText = intent.getExtras().getString(getString(R.string.EXTRA_STUFF));
Community
  • 1
  • 1
Suragch
  • 364,799
  • 232
  • 1,155
  • 1,198
7

Kotlin

Pass from First Activity

val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)

Get in Second Activity

val value = intent.getStringExtra("key")

Suggestion

Always put keys in constant file for more managed way.

companion object {
    val KEY = "key"
}
Khemraj Sharma
  • 46,529
  • 18
  • 168
  • 182
6

The passing of data between activities is mainly by means of an intent object.

First you have to attach the data to the intent object with the use of the Bundle class. Then call the activity using either startActivity() or startActivityForResult() methods.

You can find more information about it, with an example from the blog post Passing data to an Activity.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
PRABEESH R K
  • 89
  • 1
  • 1
  • This is [more or less the same](https://stackoverflow.com/questions/15243798/advantages-of-using-bundle-instead-of-direct-intent-putextra-in-android) as using the [Intent provided methods directly](https://stackoverflow.com/a/2091482/1885518) (`Intent#putExtra()`). But adds another `Bundle` and makes things more complicated. – Murmel Nov 21 '17 at 23:37
6

You can use Intent

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

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<>();
DataHolder.getInstance().setDataList(dataList);

On SecondActivity

private List<Model> dataList = DataHolder.getInstance().getDataList();
robe007
  • 2,625
  • 2
  • 25
  • 48
Sachin
  • 97
  • 1
  • 6
  • Duplicate: The intent approach is already proposed by the [top most voted answer](https://stackoverflow.com/a/7325248/1885518) and of [Sahil Mahajan Mj's answer](https://stackoverflow.com/a/12137344/1885518) and of [Mayank Saini's answer](https://stackoverflow.com/a/16733899/1885518) and [Md. Rahman's answer](https://stackoverflow.com/a/21602897/1885518), [Dilavar M's answer](https://stackoverflow.com/a/24285468/1885518), [android developer's answer](https://stackoverflow.com/a/25364957/1885518), [sahulab](https://stackoverflow.com/a/31066019/1885518). Singleton: Rodion Altshuler answer – Murmel Nov 22 '17 at 01:01
6

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 
Data",MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
edit.putInt("Session ID", session_id);
edit.commit();

To get them -

SharedPreferences pref = myContexy.getSharedPreferences("Session Data", MODE_PRIVATE);
session_id = pref.getInt("Session ID", 0);
Rohit Gurjar
  • 407
  • 4
  • 11
  • Duplicate: This approach was already propsed by [Ravi Parsania](https://stackoverflow.com/a/26484522/1885518) in 2014 – Murmel Nov 22 '17 at 01:06
5

Start another activity from this activity pass parameters via Bundle Object

Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);

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;

    getters...
    setters...
}

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);
startActivity(intent);

Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
            Gson gson = new Gson();
            Type type = new TypeToken<Employee>() {
            }.getType();
            Employee selectedEmp = gson.fromJson(empStr, type);
marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
DroidNinja
  • 827
  • 1
  • 8
  • 9
5

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);
  startActivity(intent);

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);
  startActivity(intent);

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.

Diesel
  • 512
  • 1
  • 6
  • 21
Rahul Sharma
  • 121
  • 1
  • 8
4

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:

this.extras()

To retrieve them at the other end in the Activity you switch to.

Hope that is of interest to some :)

Darius
  • 4,924
  • 5
  • 42
  • 59
  • @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 – Darius Apr 02 '18 at 09:30
4
/*
 * If you are from transferring data from one class that doesn't
 * extend Activity, then you need to do something like this.
 */ 

public class abc {
    Context context;

    public abc(Context context) {
        this.context = context;
    }

    public void something() {
        context.startactivity(new Intent(context, anyone.class).putextra("key", value));
    }
}
Oleg Vaskevich
  • 11,606
  • 5
  • 55
  • 75
Dip Pokhrel
  • 497
  • 4
  • 9
4

First Activity:

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

Second Activity:

String str= getIntent().getStringExtra("Variable name which you sent as an extra");
Nico Haase
  • 6,670
  • 34
  • 28
  • 48
3

I use static fields in a class, and get/set them:

Like:

public class Info
{
    public static int ID      = 0;
    public static String NAME = "TEST";
}

For getting a value, use this in an Activity:

Info.ID
Info.NAME

For setting a value:

Info.ID = 5;
Info.NAME = "USER!";
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
javad
  • 827
  • 12
  • 34
3

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.

...
<application android:name="MyApplication"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
....

MyApplication.java

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

public class MyApplication extends Application {
    private MainActivity mainActivity;

    @Override
    public void onCreate() {
        super.onCreate();
    }

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

MainActivity.java

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

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ((MyApplication)getApplication()).setMainActivity(this);
    }
    ...

}

MyPreferences.java

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

public class MyPreferences extends PreferenceActivity
            implements SharedPreferences.OnSharedPreferenceChangeListener {
    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        PreferenceManager.getDefaultSharedPreferences(this)
            .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
        if (!key.equals("autostart")) {
            ((MyApplication)getApplication()).getMainActivity().refreshUI();
        }
    }
}
Prags
  • 2,277
  • 2
  • 18
  • 32
Whome
  • 9,559
  • 6
  • 43
  • 59
3

Use a global class:

public class GlobalClass extends Application
{
    private float vitamin_a;


    public float getVitaminA() {
        return vitamin_a;
    }

    public void setVitaminA(float vitamin_a) {
        this.vitamin_a = vitamin_a;
    }
}

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:

GlobalClass gc = (GlobalClass) getApplication();

Then you can call for example:

gc.getVitaminA()
Patricia Heimfarth
  • 2,688
  • 2
  • 22
  • 29
  • Overriding application - this is duplicate of [Whome's answer](https://stackoverflow.com/a/20584974/1885518) – Murmel Nov 22 '17 at 00:25
3

Try this:

CurrentActivity.java

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

TargetActivity.java

Bundle b = getIntent().getExtras();
String typesofbook = b.getString("booktype");
Satan Pandeya
  • 3,460
  • 4
  • 22
  • 47
MurugananthamS
  • 2,233
  • 4
  • 16
  • 47
  • Duplicate: The `Bundle` based approach was already proposed by [PRABEESH R K](https://stackoverflow.com/a/13100481/1885518) in 2012 and [Ajay Venugopal](https://stackoverflow.com/a/28192658/1885518), [Krishna](https://stackoverflow.com/a/34355290/1885518), [Gavine Joyce](https://stackoverflow.com/a/37980963/1885518). And could be reduced to the `i.putExtras()`/`getIntent().getString()` which is proposed by 7 other answers... – Murmel Nov 22 '17 at 00:55
3

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 :

LoginActivity:

Intent intent = new 
Intent(YourLoginActivity.this,OtherActivity.class);
intent.putExtra("SESSION_ID",sessionId);
startActivity(intent);
finishAfterTransition();

OtherActivity:

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.

3

Best way to pass data to one Activity to AnothetActivity by using Intent,

Check the code snipped

ActivityOne.java

Intent myIntent = new Intent(this, NewActivity.class);
myIntent.putExtra("key_name_one", "Your Data value here");
myIntent.putExtra("key_name_two", "Your data value here");
startActivity(myIntent)

On Your SecondActivity

SecondActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view);

    Intent intent = getIntent();

    String valueOne = intent.getStringExtra("key_name_one");
    String valueTwo = intent.getStringExtra("key_name_two");
}
Mehul Solanki
  • 948
  • 8
  • 15
2

To access session id in all activities you have to store session id in SharedPreference.

Please see below class that I am using for managing sessions, you can also use same.

import android.content.Context;
import android.content.SharedPreferences;

public class SessionManager {

    public static String KEY_SESSIONID = "session_id";

    public static String PREF_NAME = "AppPref";

    SharedPreferences sharedPreference;
    SharedPreferences.Editor editor;
    Context mContext;

    public SessionManager(Context context) {
        this.mContext = context;

        sharedPreference = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        editor = sharedPreference.edit();
    }


    public String getSessionId() {
        return sharedPreference.getString(KEY_SESSIONID, "");
    }

    public void setSessionID(String id) {
        editor.putString(KEY_SESSIONID, id);
        editor.commit();
        editor.apply();
    }   
}

//Now you can access your session using below methods in every activities.

    SessionManager sm = new SessionManager(MainActivity.this);
sm.getSessionId();



//below line us used to set session id on after success response on login page.

    sm.setSessionID("test");
ppreetikaa
  • 1,025
  • 2
  • 14
  • 22
1

Write following code in CurrentActivity.java

Intent i = new Intent(CurrentActivity.this, SignOutActivity.class);
i.putExtra("SESSION_ID",sessionId);
startActivity(i);

Access SessionId in SignOutActivity.java is following way

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_out);
    Intent intent = getIntent();
    
    // check intent is null or not
    if(intent != null){
        String sessionId = intent.getStringExtra("SESSION_ID");
        Log.d("Session_id : " + sessionId);
    }
    else{
        Toast.makeText(SignOutActivity.this, "Intent is null", Toast.LENGTH_SHORT).show();
    }
}
The Billionaire Guy
  • 2,468
  • 24
  • 23
Android Player_Shree
  • 1,212
  • 12
  • 31
  • This is a duplicate of the 3 years older [top most voted answer](https://stackoverflow.com/a/7325248/1885518) and of [Sahil Mahajan Mj's answer](https://stackoverflow.com/a/12137344/1885518) and of [Mayank Saini's answer](https://stackoverflow.com/a/16733899/1885518) and [Md. Rahman's answer](https://stackoverflow.com/a/21602897/1885518) and [Dilavar M's answer](https://stackoverflow.com/a/24285468/1885518) and [android developer's answer](https://stackoverflow.com/a/25364957/1885518), [sahulab](https://stackoverflow.com/a/31066019/1885518) – Murmel Nov 22 '17 at 01:11
1

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

MageNative
  • 652
  • 5
  • 14
  • Duplicate: the static approach was already proposed by [ComputerSaysNo](https://stackoverflow.com/a/13078360/1885518) and [Przemek](https://stackoverflow.com/a/17379703/1885518) and [javadaskari](https://stackoverflow.com/a/19982438/1885518) and [Mohamed Selim](https://stackoverflow.com/a/33707743/1885518) – Murmel Nov 22 '17 at 01:13
1

If you use kotlin:

In MainActivity1:

var intent=Intent(this,MainActivity2::class.java)
intent.putExtra("EXTRA_SESSION_ID",sessionId)
startActivity(intent)

In MainActivity2:

if (intent.hasExtra("EXTRA_SESSION_ID")){
    var name:String=intent.extras.getString("sessionId")
}
Vadim Kotov
  • 7,103
  • 8
  • 44
  • 57
Ali hasan
  • 543
  • 8
  • 8
1

Your data object should extend Parcelable or Serializable class

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

To do this in Java:

startActivity(new Intent(this, MainActivity.class).putExtra("userId", "2"));
Mohsinali
  • 425
  • 6
  • 11
1

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

intent.putExtra("KEY","VALUE");

startActivity(intent);

In Activity B (the destination)->

Intent intent =getIntent();

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

Here you will get data for key "KEY"

FOR BETTER USE ALWAYS KEYS SHOULD BE STORED IN A CLASS FOR SIMPLICITY AND IT WILL HELP IN MINNIMISE THE RISK OF TYPING ERRORS

Like this:

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

Now In ACTIVITY A:

intent.putExtra(Constants.KEY,"VALUE");

In Activity B:

String data =intent.getString(Constants.KEY);
phrogg
  • 705
  • 1
  • 12
  • 25
Nitish
  • 151
  • 3
  • 9
1

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 WeakReference<Context> mContext;

    private static SharedMethode sharedMethode = new SharedMethode();

    private SharedMethode() {
        super();
    }

    public static SharedMethode getInstance() {
        return sharedMethode;
    }

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

        mContext = new WeakReference<Context>(context);
    }

    public boolean contextAssigned() {
        return mContext != null && mContext.get() != null;
    }

    public Context getContext() {
        return mContext.get();
    }

    public void freeContext() {
        if (mContext != null) mContext.clear();
        mContext = null;
    }
}

- STEP 03 :: Play with code in First Activity

public class FirstActivity extends Activity implements SharedCallback {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

        // call playMe from here or there
        playMe();
    }

    private void playMe() {
        SharedMethode.getInstance().setContext(this);
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }

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

}

- STEP 04 :: Finalize the game in SecondActivity

public class SecondActivity extends Activity {

    private SharedCallback sharedCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

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

            // to prevent memory leak
            SharedMethode.freeContext();
        }

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

    }

    @Override
    protected void onDestroy() {
        sharedCallback = null;
        super.onDestroy();
    }

}
  • STEP 05 :: you can also implement a backword callback (from First to Second) to get some results from SecondAvtivity or call some methods
tdjprog
  • 631
  • 6
  • 10
  • Terrible idea ... you should always take into account worst case scenarion ... which is: On Android OS only one Activity is running - others are killed – Selvin Nov 30 '20 at 13:01
1

Create new Intent inside your current activity

String myData="Your string/data here";
Intent intent = new Intent(this, SecondActivity.class);    
intent.putExtra("your_key",myData);
startActivity(intent);

Inside your SecondActivity.java onCreate() Retrieve those value using key your_key

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String myData = extras.getString("your_key");
    }  
}
Vipul Prajapati
  • 1,017
  • 7
  • 11
1

There are more than one ways of passing data between activities and other components of android app. One is using intents and parcelable as mentioned in lot of answers already.

Another elegent way is using Eventbus library.

From emitting activity:

EventBus.getDefault().postSticky("--your Object--");

In recv activity:

EventBus.getDefault().removeStickyEvent("--Object class--")

Other points to consider:

  1. Gives more freedom, You can pass complex objects without modifying them in any form.
  2. Not restricted to passing data between activities only, Once you set up the library, you can use it to pass data from one place to another in the app plumbing. For example use this for BottomSheetMenu to activity communication.
  3. Stable library.
  4. simplifies the communication between components
  5. decouples event senders and receivers
  6. performs well with UI artifacts (e.g. Activities, Fragments) and background threads
  7. avoids complex and error-prone dependencies and life cycle issues
  8. is fast; specifically optimized for high performance
  9. is tiny (~60k jar)
  10. is proven in practice by apps with 1,000,000,000+ installs
  11. has advanced features like delivery threads, subscriber priorities, etc.
humble_wolf
  • 952
  • 11
  • 20
0

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();
                instance.id = id;
                instance.name = name;
            }
            return instance;
        }
    }
    
Murmel
  • 4,141
  • 38
  • 45
Rodion Altshuler
  • 1,583
  • 14
  • 29
0

I use public static fields to store shared data between activities, but to minimize its side effects, you may:

  • Make only one field, or as few as possible, and reuse them, make them of type object and cast it to desired type in the receiving activity.
  • Whenever any of them isn't useful anymore, set it explicitly to null to be collected by the garbage collector, before the next assignment.
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Mohamed Selim
  • 2,839
  • 1
  • 24
  • 34
0

//Your problem is you want to store session id after sign in and available that session id for each activity where you want to logout.

//The solution of your problem is you have to store your session id after successful login in a public variable. and whenever you need session id for logout you can access that variable and replace variables value to zero.

//Serializable class

public class YourClass  implements Serializable {
     public long session_id = 0;
}
0

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
           model.getSomething();
    }
}

In the first activity, start the second activity like below

DestinationActivity.open(this,model);
Vincent Mungai
  • 142
  • 2
  • 3
0

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

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

InActivity 2:

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

2.Through SharedPreference

  Activity1:

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

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

pref.getString("key_name", null); // getting String
MurugananthamS
  • 2,233
  • 4
  • 16
  • 47
0
 Intent intent = new Intent(getBaseContext(), SomeActivity.class);
 intent.putExtra("USER_ID", UserId);
 startActivity(intent);

 On SomeActivity : 

 String userId= getIntent().getStringExtra("("USER_ID");
Raviraj
  • 536
  • 6
  • 12
0

You can work with intent

String sessionId = "my session id";

    startActivity(new Intent(getApplicationContext(),SignOutActivity.class).putExtra("sessionId",sessionId));
Richard Kamere
  • 428
  • 9
  • 8
0

Using Bundle @link https://medium.com/@nikhildhyani365/pass-data-from-one-activity-to-another-using-bundle-18df2a701142
//copy from medium

           Intent I =  new Intent(MainActivity.this,Show_Details.class);

            Bundle b = new Bundle();


            int x = Integer.parseInt(age.getText().toString());
            int y = Integer.parseInt(className.getText().toString());

            b.putString("Name",name.getText().toString());

            b.putInt("Age",x);
            b.putInt("ClassName",y);

            I.putExtra("student",b);

            startActivity(I);

Using Intent @link https://android.jlelse.eu/passing-data-between-activities-using-intent-in-android-85cb097f3016

Ashif
  • 178
  • 1
  • 9