2015-09-24 60 views
2

我很熟悉在我的應用中實現Admobs,但是我正在努力將活動更改爲片段。在片段中顯示Admob橫幅時出錯

我得到一個NullPointerException。我相信使用getView()可能會導致我的問題。

AdMob聯播代碼:片段

//CREATE BANNER ADD 
    private void createAdmobBanner() 
    { 
     // Create an ad. 

     adView = (com.google.android.gms.ads.AdView) getView() 
       .findViewById(R.id.adView); 
     AdRequest adRequest = new AdRequest.Builder() 

     // Add a test device to show Test Ads 
       .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) 
       // .addTestDevice("B3827F13FB335337F4CA0F350B78A866") 
         .build(); 


       // Load ads into Banner Ads 
      adView.loadAd(adRequest); 

    } 

XML AdMob聯播佈局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:ads="http://schemas.android.com/apk/res-auto" 
android:id="@+id/adViewHolder" 
android:layout_width="fill_parent" 
android:layout_height="@dimen/ad_bottom_height" 
android:layout_marginTop="1dp" 

android:gravity="center_vertical" 
android:orientation="horizontal" > 

<com.google.android.gms.ads.AdView 
    android:id="@+id/adView" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    ads:adSize="SMART_BANNER" 
    ads:adUnitId="ca-app-pub-xxxx/xxxx" 
    /> 

</LinearLayout> 


<RelativeLayout 
    android:layout_width="fill_parent" 
    android:layout_height="@dimen/bottom_bar_height" 

    android:orientation="horizontal" > 

<Button 
    android:id="@+id/button1" 
    android:text="Refresh Scores" 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent" 
    android:textSize="11dp" 
android:layout_weight="1" 
     /> 

注:我用......包括佈局= 「@佈局/ admob_ad」/>在我的片段佈局的xml 。

代碼錯誤:

09-24 22:04:02.429:E/AndroidRuntime(5375):顯示java.lang.NullPointerException:嘗試調用虛擬方法「無效com.google.android.gms.ads。 AdView.loadAd(com.google.android.gms.ads.AdRequest)'空對象引用 09-24 22:04:02.429:E/AndroidRuntime(5375):at info.androidhive.slidingmenu.ChampionsFragment.createAdmobBanner ChampionsFragment.java:391)

回答

0

我遇到類似的問題,當我在國土資源文件密切檢查 有我的活動二國土資源文件:

  1. \res\layout\activity_main_lauch.xml
  2. \res\layout-v21\activity_main_lauch.xml

我對矯正單個文件中,因此它被扔錯誤。當我在兩個文件中應用更改時,它開始工作。