3

我从我的一些用户那里得到了一个 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));
    }
}

本质上,我所做的只是检查保存的首选项布尔值,并根据它的值在按钮上设置标签,或者将它们设置为空白。

有人可以请教吗?

谢谢

4

4 回答 4

7

我认为关键是当用户恢复活动时,布局没有设置,因此 afindViewById()没有要查找的“锚点”,因此返回 null。

您可以将调用移至setContentView()fromonCreateonResume(假设您没有在 中引用视图onCreate。对于正常使用,这与 Android 生命周期中的区别没有什么不同,在用户可以与活动交互onResume之后和之前直接调用。onCreate

实际上,在某些应用程序中存在一个错误,您访问一个活动,然后启动另一个活动,也许将应用程序留给另一个活动,然后返回然后(通过后退按钮)返回到第一个活动。在这里你突然看到一个黑屏。这是因为系统“交换”了第一个活动并且只在返回时onResume被调用,而不是onCreate,所以没有机会再次加载布局。

于 2012-01-26T20:36:38.030 回答
3

做所有这些 ((Button)findViewById(R.id.speakEnglishButton)).setText(""); ....在 onCreate()

添加

private Button mSpeakEngButton;
.....

作为类变量,在 onCreate() 中初始化它们

public void onCreate() {

   ....
   mSpeakEngButton = ((Button)findViewById(R.id.speakEnglishButton));
}

稍后在代码中,您可以将它们的值修改为 mSpeakEngButton.setWhatever()

于 2012-01-26T21:09:35.933 回答
2

很可能是由于

((Button)findViewById(R.id.speakEnglishButton));

返回空值。如果找不到这样的资源,就会发生这种情况。我突然想到一个原因:您的布局中没有默认资源。这意味着:您必须至少有一个“默认”布局,它适用于每种语言/方向/...应该放在文件夹“布局”中。简单的“布局”。

于 2012-01-26T20:36:08.060 回答
-1

如果您将 setContentView() 保留在 onResume() 而不是 onCreate(),它会给出 inflate 异常,我已经尝试过了。

于 2013-11-11T11:00:58.263 回答