修改按钮时onResume中的NullPointerException,为什么?

Jim*_*mmy 3 android android-ui android-2.1-eclair android-activity

我从一些用户那里得到了一个N​​ullPointerException,我无法发现问题所在,它被抛到了这一行:

((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));
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,我正在做的是检查保存的首选项布尔值,并根据其值,我要么在按钮上设置标签,要么将它们设置为空白.

任何人都可以建议吗?

谢谢

Hei*_*upp 7

我认为重点是,当用户恢复活动时,布局没有设置,因此findViewById()没有'锚'要查找,因此返回null.

您可以将呼叫setContentView()onCreateto 移动到onResume(假设您没有引用视图onCreate.对于正常使用,这与Android生命周期没有区别,在用户可以与活动交互之前和之后onResume直接调用onCreate.

实际上,在某些应用程序中有一个错误,您访问某个活动,然后启动另一个活动,可能会将该应用程序留给另一个活动,返回,然后返回(通过后退按钮)到第一个活动.突然间,你看到一个黑屏.这是因为系统"交换"了第一个活动并且仅在返回时onResume被调用,但没有onCreate,因此没有机会再次加载布局.