Pergunta

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?

Foi útil?

Solução

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

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top