adView抛出Null指针异常

时间:2014-12-20 14:29:27

标签: android admob

请找到以下代码,adView正在提供nullpointerexception。

    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    // Prepare the Interstitial Ad
            interstitial = new InterstitialAd(MainActivity.this);
            // Insert the Ad Unit ID
            interstitial.setAdUnitId("ca-app-pub-6117491189465387/7628536955");

    //Locate the Banner Ad in activity_main.xml
    AdView adView = (AdView)findViewById(R.id.adView);

    // Request for Ads
    AdRequest.Builder adRequestBuilder=new AdRequest.Builder();

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

    // Load ads into Banner Ads


     adView.setAdSize(AdSize.BANNER);
        adView.setAdUnitId("ca-app-pub-6117491189465387/7628536955");
        adView.loadAd(adRequestBuilder.build());

    interstitial.setAdListener(new AdListener() {
        public void onAdLoaded() {
            // Call displayInterstitial() function
            displayInterstitial();
        }

    });

我被击中了2天,请告诉我错误的地方

1 个答案:

答案 0 :(得分:0)

我没有看到你的setContentView()方法()。 adview可以为null,因为您要么未设置要使用的布局,要么在初始化adview后调用setContentView()。你应该这样:

 setContentView(R.layout.activity_main);
AdView adView = (AdView)findViewById(R.id.adView);

如果我错了,请发布onCreate()方法,logcat堆栈跟踪和布局文件的完整内容