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?
Asked
Active
Viewed 67 times
-1
-
how you open from activity 1 to activity 3? – John Joe May 09 '20 at 06:53
-
By going through the activity 2, but its little hard to pass from activity 1 to activity 2 and then to activity 3, how can I directly pass it? – theKnifer May 09 '20 at 06:55
-
1how about this ? https://stackoverflow.com/a/12282529/5156075 – John Joe May 09 '20 at 06:57
3 Answers
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