gpt4 book ai didi

java - Chronometer 为空,即使父类初始化了它

转载 作者:行者123 更新时间:2023-11-29 20:29:42 25 4
gpt4 key购买 nike

我遇到了这个奇怪的问题,它困扰着我。我不明白为什么我在 MainActivity 中初始化计时器时会得到这个 NullPointerException。如果我在 SecondActivity 中初始化 chronometer,程序运行良好。

希望有人能解决这个问题......

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Chronometer.setOnChronometerTickListener(android.widget.Chronometer$OnChronometerTickListener)' on a null object reference

-

public class MainActivity extends AppCompatActivity {

protected Chronometer chronometer;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

//chronometer gets initialised here but it's still null appearantly
chronometer = (Chronometer) findViewById(R.id.chronometer1);

//this works
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#cd2626")));
}
}

-

public class SecondActivity extends MainActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);

//if chronometer gets initialised again, program does work.
//chronometer = (Chronometer) findViewById(R.id.chronometer1)
}
}

最佳答案

包括setContentView(R.layout.main_layout);在您的主要 Activity 中,否则 findviewbyid 将无法找到计时表,并且它将始终显示空异常

关于java - Chronometer 为空,即使父类初始化了它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32171024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com