android-studio - 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.
解决方案
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
推荐阅读
- reactjs - ag-grid 反应:gridApi 未定义
- outlook - 自定义连接器不起作用“从连接器收到错误...”
- angular - 错误:ExpressionChangedAfterItHasBeenCheckedError:以前的值:'ng-untouched: true'。当前值:'ng-untouched: false'
- javascript - 我无法在本地计算机上运行 D3 代码
- flutter - How to make dialog scrollable?
- c# - 当我使用 C++ Dll 中的函数时,Unity 中的运行时错误
- angular - 使用自定义数据源在 mat-table 中排序、分页和过滤?
- delphi - Delphi:TTask 似乎只有第一次慢
- apache-spark - Pyspark:将函数应用于匹配多个数据帧的分区
- firebase - 无法在本地触发 Firestore 更改