UMAR-MOBITSOLUTIONS
UMAR-MOBITSOLUTIONS

Reputation: 78014

How do I pass data between Activities in Android application?

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

Upvotes: 1539

Views: 1269840

Answers (30)

angryITguy
angryITguy

Reputation: 9561

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 to launch the intent. Which then provides easy setup and retrieval 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 too. A simple example above, but you get the idea.

Upvotes: 50

Gavine Joyce
Gavine Joyce

Reputation: 389

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

Upvotes: 23

user5876477
user5876477

Reputation:

Your data object should extend Parcelable or Serializable class.

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

Upvotes: 2

Nitish
Nitish

Reputation: 323

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

Upvotes: 3

Vincent Mungai
Vincent Mungai

Reputation: 302

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

Upvotes: 1

Khushboo Aggarwal
Khushboo Aggarwal

Reputation: 135

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 through 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 to call getIntent().getStringExtra("SESSION_ID"); Also, make sure to check if the intent is null and the key you are passing in the intent should be the 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 use AppSharedPreferences to store your sessionId and get it from that wherever needed.

Upvotes: 2

Erich Douglass
Erich Douglass

Reputation: 52002

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 the next activity:

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

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

Upvotes: 1461

Vipul Prajapati
Vipul Prajapati

Reputation: 1183

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

Upvotes: 1

Richard Kamere
Richard Kamere

Reputation: 799

You can work with the intent.

String sessionId = "my session id";
startActivity(new Intent(getApplicationContext(),SignOutActivity.class).putExtra("sessionId",sessionId));

Upvotes: 0

Rahul Sharma
Rahul Sharma

Reputation: 121

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

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

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

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

2nd way: You can create a bundle object and put values in a bundle and then put the 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 the onCreate method, retrieve those values which you pass from the 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 retrieve value from one activity to another.
  }

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

Upvotes: 6

rajeev ranjan
rajeev ranjan

Reputation: 230

In other way you can pass data using Interfaces.

We have 2 activity A,B then what will I do, create an interface like:

public interface M{
    void data(String m);
}

then You Can call assign value to this method like below in Class A as code below:

public class A extends AppCompatActivity{
    
   M m;   //inteface name
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a);
       
        m= (M) getActivity();

    //now call method in interface and send data im sending direct you can use same on click

    m.data("Rajeev");
    }
}

Now You have to implement that interface in class B:

public class B extends AppCompatActivity implements M{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.b);
    }

    @Override
    public void data(String m) {
        you can use m as your data to toast the value here it will be same value what you sent from class A
    }
}

Upvotes: -3

Shreeya Chhatrala
Shreeya Chhatrala

Reputation: 1449

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

Upvotes: 7

Khemraj Sharma
Khemraj Sharma

Reputation: 59004

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"
}

Upvotes: 20

humble_wolf
humble_wolf

Reputation: 1668

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.

Upvotes: 1

Ashif
Ashif

Reputation: 471

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

Upvotes: 0

tdjprog
tdjprog

Reputation: 719

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

Upvotes: 1

Parth_Darji
Parth_Darji

Reputation: 69

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

Upvotes: 2

Raviraj
Raviraj

Reputation: 926

 Intent intent = new Intent(getBaseContext(), SomeActivity.class);
 intent.putExtra("USER_ID", UserId);
 startActivity(intent);

 On SomeActivity : 

 String userId= getIntent().getStringExtra("("USER_ID");

Upvotes: 0

Mehul Solanki
Mehul Solanki

Reputation: 1141

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

Upvotes: 3

MurugananthamS
MurugananthamS

Reputation: 2405

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

Upvotes: 0

Mohsinali
Mohsinali

Reputation: 553

To do this in Java:

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

Upvotes: 1

suresh madaparthi
suresh madaparthi

Reputation: 376

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

Upvotes: 5

Sachin
Sachin

Reputation: 107

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

Upvotes: 7

THANN Phearum
THANN Phearum

Reputation: 2079

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.

Upvotes: 10

Darius
Darius

Reputation: 5269

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

Upvotes: 5

user914425
user914425

Reputation: 16483

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.

Upvotes: 1525

Whome
Whome

Reputation: 10400

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

Upvotes: 3

Suragch
Suragch

Reputation: 512506

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

Upvotes: 77

Rodion Altshuler
Rodion Altshuler

Reputation: 1783

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

Upvotes: 0

DroidNinja
DroidNinja

Reputation: 1007

Start another activity from this activity pass parameters via Bundle Object

Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "[email protected]");
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);

Upvotes: 6

Related Questions