java - 在android中使用在不同Java类中声明的变量
问题描述
我正在与安卓工作室合作。
我在 MainActivity.java 文件中声明了一个变量,并且想在另一个类中使用相同的变量,比如 Records.java 文件。
在 MainActivity.java 中:
public void parse(String response)
{
//some code
String token = //some code //use code in Records class
Intent intent = new Intent(MainActivity.this,Records.class);
startActivity(intent);
}
在 RecordsActivity.java 中:
public class Records extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//use token variable here
}
那么,根据上面的代码,我想使用在 MainActivity 中声明的 token 变量并在 Records.java 中使用它是否允许这样做?
解决方案
请按照以下方式进行:
String token = //some code //use code in Records class
Intent intent = new Intent(MainActivity.this,Records.class);
intent.putExtra("token" , token )
startActivity(intent);
在 onCreate() 中获取意图使用:
Intent intent = getIntent();
String sToken= intent.getStringExtra("token");
推荐阅读
- php - “Apache 环境”、“环境”和“PHP 变量”之间有什么区别?
- java - 我的分割序列代码并不能解决它所面临的所有问题
- asp.net-mvc - 在 WCF 服务和 MVC 5 之间共享 HttpContext
- laravel - 从 belongsToMany 关系中获取用户
- python - 如何使用机器学习从数据中检测英语单词
- c# - FlowDocument 的网格替代方案?
- android - 与 Raspberry Pi 对话的 Android 应用程序
- sql - 我想从员工表中搜索工作和薪水,但我收到了无效关系运算符之类的错误
- java - GsonFromJson:如何用数组结构序列化和反序列化
- node.js - 异步返回对象并在nodejs中等待