繁体   English   中英

如何在整个类中使用变量并将变量传递到新的android活动中?

[英]How do I pass variables into a new android activity, with the ability to use them throughout the class?

我正在尝试将变量传递到活动中,但是正在获取空对象引用。

我的意图声明使用了putExtra()

public void launch_test(View view) {
    playsound.start();
    Intent launch_test = new Intent(this, test.class);
        launch_test.putExtra("NUM_ROWS", 4);
        launch_test.putExtra("NUM_COLS", 4);
    startActivity(launch_test);
}

我的活动课(测试)要求额外的费用,

public class test extends Activity {
Intent launch_test = getIntent();
Bundle extras = launch_test.getExtras();

int NUM_ROWS = launch_test.getIntExtra("NUM_ROWS", 0);
int NUM_COLS = launch_test.getIntExtra("NUM_COLS", 0);

Button buttons[][] = new Button[NUM_ROWS][NUM_COLS];

etc...

但是当我尝试在模拟器中运行它时,我得到的是空对象引用。

我假设可以使用IF语句检查是否为空,但是Android Studio不允许我在代码的这一部分使用if语句。 如果我将IF语句放入OnCreate函数中,那么我将无法按照我希望的方式在整个类中使用变量。

我是android编程的新手,如果感到困惑,对不起!

如果您只想使用您的代码,请对其进行更正,请使用:extras.getIntExtra而不是launch_test.getIntExtra

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM