我遇到了这个奇怪的问题,这困扰着我。我不明白为什么在MainActivity中初始化计时器时会收到此NullPointerException异常。如果我在SecondActivity中初始化计时器,则该程序可以正常运行。
希望有人可以解决这个问题...
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);在您的mainactivity中,否则findviewbyid将无法找到计时器,并且将始终显示null异常