0

I'm getting a nullpointer exception in the following code in my application :

@Override
protected void onResume() {
    super.onResume();    //To change body of overridden methods use File | Settings | File Templates.

    // Create the adView
    adView = new AdView(this, AdSize.BANNER, MY_AD_UNIT_ID);

    LinearLayout layout = (LinearLayout) findViewById(R.id.ad_layout);

    // Add the adView to it
    layout.addView(adView); //NullPointerException here

    // Initiate a generic request to load it with an ad
    adView.loadAd(new AdRequest());


    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    boolean isButtonLabelsEnabled = sp.getBoolean("isButtonLabelsEnabled", false);
    if (!isButtonLabelsEnabled) {
        stripLabels();
    } else {
        setContentView(R.layout.languageselection);
    }
}

I can't replicate this issue, I've played around with all the features in my app on both the emulator, a galaxy S2 device, and a ZTE blade but I can't find any issues.

I'm getting a lot of users report this, but they don't give any indication to why, just that it forces close when they try to open it.

Perhaps I'm not using the android life-cycle correctly?

As a workaround, I've wrapped the AdMob stuff in a try/catch so it can pass through.

Any ideas?

Lion
  • 17,515
  • 21
  • 76
  • 104
Jimmy
  • 15,225
  • 38
  • 120
  • 211
  • This sounds like for some R.id.ad_layout is not found. Only reason I can think of why this could happen on some devices, and not all, would be different layouts for different screen sizes for example. For which some of them you have different ids. – harism Jan 01 '12 at 17:48

2 Answers2

1

Try getting your LinearLayout object in onCreate method instead of getting it in onResume method. Hope this works for you.

Usama Sarwar
  • 8,520
  • 7
  • 50
  • 79
0

Try like this:

private LinearLayout layout;

onCreate(){

       layout = (LinearLayout) findViewById(R.id.ad_layout);

}


@Override
protected void onResume() {
    super.onResume();    //To change body of overridden methods use File | Settings | File Templates.

    // Create the adView
    adView = new AdView(this, AdSize.BANNER, MY_AD_UNIT_ID);

    //LinearLayout layout = (LinearLayout) findViewById(R.id.ad_layout);

    // Add the adView to it
    layout.addView(adView); //NullPointerException here

    // Initiate a generic request to load it with an ad
    adView.loadAd(new AdRequest());


    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    boolean isButtonLabelsEnabled = sp.getBoolean("isButtonLabelsEnabled", false);
    if (!isButtonLabelsEnabled) {
        stripLabels();
    } else {
        setContentView(R.layout.languageselection);
    }
}
jainal
  • 2,903
  • 1
  • 17
  • 18