0

我得到一個空指針異常,在我的應用程序下面的代碼:的NullPointerException在的onResume,涉及AdMob的,但不知道爲什麼

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

我不能複製這個問題,我周圍玩我的應用在模擬器,Galaxy S2設備和中興通訊刀片上的所有功能,但是我找不到任何問題。

我收到很多用戶報告,但他們沒有給出任何跡象,爲什麼,只是當他們試圖打開它時強制關閉。

也許我沒有正確使用android生命週期?

作爲一種解決方法,我將AdMob內容封裝在try/catch中,以便它可以通過。

任何想法?

+0

這聽起來像一些R.id.ad_layout沒有找到。只有理由,我可以想到爲什麼在某些設備上可能發生這種情況,而不是所有情況,例如,對於不同的屏幕尺寸,將會是不同的佈局。對於其中一些你有不同的ID。 – harism 2012-01-01 17:48:45

回答

0

嘗試這樣的:

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

是我們得到問題... – 2013-01-29 12:52:57

1

嘗試獲得在onCreate方法您的LinearLayout對象,而不是得到它的onResume方法。希望這對你有用。

相關問題