修改按钮NullPointerException异常时,在onResume,为什么呢? [英] NullPointerException in onResume when modifying Buttons, why?

查看:151
本文介绍了修改按钮NullPointerException异常时,在onResume,为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到我的一些用户提出了一个NullPointerException异常,我无法发现什么问题,它扔在这条线:

I'm getting a NullPointerException raised from a number of my users, and I'm unable to spot what the issue is, it is thrown on this line :

((按钮)findViewById(R.id.speakEnglishButton))的setText();

我无法看到什么是错的,按键的存在具有该ID,它编译好,工作正常在我的仿真器和2台设备,但我越来越被张贴在我的开发人员控制台约100家左右的误差用户在这个版本。

I'm unable to see what is wrong, the button exists with that Id, it compiles fine, works fine on my emulator and 2 devices, however I'm getting about 100 or so errors being posted in my developer console for users on this version.

仔细研究onResume:

Looking closer at the 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));
    }
}

从本质上讲,我做的是检查保存preference布尔值,并根据其价值,我要么设置上的按钮标签,或将它们设置为空白。

Essentially, all I'm doing is checking for a saved preference boolean, and depending on its value I'm either setting labels on buttons, or setting them to blanks.

任何人都可以请指教?

感谢

推荐答案

做所有这些的((按钮)findViewById(R.id.speakEnglishButton))的setText()。 .... 中的onCreate()

Do all of those ((Button)findViewById(R.id.speakEnglishButton)).setText(""); .... in onCreate()

添加

private Button mSpeakEngButton;
.....

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

As class variables, initialize them in onCreate()

public void onCreate() {

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

后来在code,你可以修改它们的值mSpeakEngButton.setWhatever()

Later in code you can modify their values as mSpeakEngButton.setWhatever()

这篇关于修改按钮NullPointerException异常时,在onResume,为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆