首页 > 解决方案 > How to pass data between activities that don't follow one another

问题描述

I have a scenario where I want to keep the username value I entered in my login activity and send this value, not to the following activity Intent intent = new Intent(LoginActivity.this, SecondActivity.this), but to another activity further in the appThirdActivity or FourthActivity. So basically the question is how do you pass data between non successive activities.

标签: android-studio

解决方案


Its very simple you can add Shared Preferences in your login activity add the following code

First, make a constant

public static final String USERNAME = "0";//Write this at the start

//Then add this inside a function 
SharedPreferences sharedPreferences = getSharedPreferences("username", 0);
Editor editor = sharedPreferences.edit();
editor.putString(USERNAME, username);//username is your username.
editor.apply();

Then maybe in your third/fourth activity add this in function onCreate()

SharedPreferences sharedPreferences = getSharedPreferences("username", 0);
String Username = sharedPreferences.getString(USERNAME, "");
//Now you can use the String Username wherever you want

推荐阅读