我从我的一些用户那里得到了一个 NullPointerException,我无法发现问题是什么,它被抛到这一行:
((Button)findViewById(R.id.speakEnglishButton)).setText("");
我看不出有什么问题,按钮与那个 ID 一起存在,它编译正常,在我的模拟器和 2 台设备上工作正常,但是我的开发者控制台中发布了大约 100 个左右的错误此版本的用户。
仔细观察 onResume :
@Override
protected void onResume()
{
super.onResume();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean isButtonLabelsEnabled = sp.getBoolean("isButtonLabelsEnabled", false);
if (!isButtonLabelsEnabled)
{
((Button)findViewById(R.id.speakEnglishButton)).setText("");
((Button)findViewById(R.id.speakFrenchButton)).setText("");
((Button)findViewById(R.id.speakSpanishButton)).setText("");
((Button)findViewById(R.id.speakGermanButton)).setText("");
((Button)findViewById(R.id.speakItalianButton)).setText("");
}
else
{
((Button)findViewById(R.id.speakEnglishButton)).setText(getString(R.string.btnLblEnglish));
((Button)findViewById(R.id.speakFrenchButton)).setText(getString(R.string.btnLblFrench));
((Button)findViewById(R.id.speakSpanishButton)).setText(getString(R.string.btnLblSpanish));
((Button)findViewById(R.id.speakGermanButton)).setText(getString(R.string.btnLblGerman));
((Button)findViewById(R.id.speakItalianButton)).setText(getString(R.string.btnLblItalian));
}
}
基本上,我所做的只是检查保存的首选项 bool 值,并根据它的值在按钮上设置标签,或将它们设置为空白。
谁能给个建议?
谢谢
最佳答案
我认为关键在于,当用户恢复 Activity 时,布局未设置,因此 findViewById()
没有要查找的“ anchor ”,因此返回 null。
您可以将对 setContentView()
的调用从 onCreate
移动到 onResume
(前提是您没有在 中引用 View onCreate
。对于正常使用,这与 Android 生命周期中没有区别,onResume
在 onCreate
之后和用户可以与 Activity 交互之前直接调用。
实际上,在某些应用程序中存在一个错误,您访问一个 Activity ,然后开始另一个 Activity ,也许离开应用程序进行另一个 Activity ,返回然后返回(通过后退按钮)到第一个 Activity 。突然间,您会看到黑屏。这是因为系统“交换”了第一个 Activity ,并且在返回时只调用了 onResume
,而不是 onCreate
,所以没有机会在那里再次加载布局。
关于android - 修改 Button 时 onResume 出现 NullPointerException,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9024913/