androidandroid-activityandroid-2.1-eclair

NullPointerException in onResume when modifying Buttons, why?


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 :

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

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.

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));
    }
}

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.

Can anyone please advise?

Thanks


Solution

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

    Add

    private Button mSpeakEngButton;
    .....
    

    As class variables, initialize them in onCreate()

    public void onCreate() {
    
       ....
       mSpeakEngButton = ((Button)findViewById(R.id.speakEnglishButton));
    }
    

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