-1

In android, to pass a variable from activity 1 to activity 2, intents are used. But how to pass variables from activity 1 to activity 3. In my project, I am getting a id from user in login activity, which is needed in other activity, but it is not the immediate activity to it. How to do this?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
theKnifer
  • 25
  • 6

3 Answers3

1

You can use SharedPreference

Setting values in Preference:

SharedPreferences.Editor editor = getSharedPreferences("mypref", MODE_PRIVATE).edit();
 editor.putString("name", "john");
 editor.putInt("id", 12);
 editor.apply();

Retrieve data from preference:

SharedPreferences prefs = getSharedPreferences("mypref", MODE_PRIVATE); 
String name = prefs.getString("name", "");
int idName = prefs.getInt("id", 0); 
Jimale Abdi
  • 2,574
  • 5
  • 26
  • 33
1

Create a static variable in your Helper class,

public class Helper {
    public static int user_id;
}

Set its value in activity A:

    Helper.user_id = 309; // id you want to save. 

And then access its value in Activity B:

    if(Helper.user_id != 0){
         user_id = Helper.user_id;
    }
Hafiza
  • 800
  • 8
  • 15
1

You can pass the id from one activity to another activity using the eventBus

Gradle

implementation 'org.greenrobot:eventbus:3.2.0'

Activity-1: where you need to pass id

EventBus.getDefault().post(new MessageEvent());

Activity-3 : where you need to receive id

Register eventBus

@Override
 public void onStart() {
     super.onStart();
     EventBus.getDefault().register(this);
 }

 @Override
 public void onStop() {
     super.onStop();
     EventBus.getDefault().unregister(this);
 }

Prepare subscribers

Subscribers implement event handling methods (also called “subscriber methods”) that will be called when an event is posted. These are defined with the @Subscribe annotation.

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(MessageEvent event) {/* Do something */};
Bijal Sutariya
  • 214
  • 1
  • 5