首页 > 解决方案 > 在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 中使用它是否允许这样做?

标签: javaandroid

解决方案


请按照以下方式进行:

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");

推荐阅读