调用mAdView.loadAd时出现NullPointerException

时间:2015-06-17 08:58:29

标签: android nullpointerexception admob

我在自己的应用中添加了Google广告。它们在我的OnePlus One设备上运行良好。我不明白,为什么它不起作用。我甚至添加了检查,如果对象在加载之前为null。当我在Nexus 7虚拟设备上测试它时。它给了我这个例外:

 java.lang.RuntimeException: Unable to start activity ComponentInfo{koemdzhiev.com.eggyegg/koemdzhiev.com.eggyegg.MainActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
        at android.app.ActivityThread.access$600(ActivityThread.java:130)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at koemdzhiev.com.eggyegg.MainActivity.onCreate(MainActivity.java:51)
        at android.app.Activity.performCreate(Activity.java:5008)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)

这是我在主要活动中的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Google ads
    AdView mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    if(adRequest != null) {
        mAdView.loadAd(adRequest);
    }

1 个答案:

答案 0 :(得分:4)

我找到了解决方案,很简单。我没有检查adRequest是否为null,而是检查了mAdView,如下所示:

 AdView mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    if(mAdView != null) {
        mAdView.loadAd(adRequest);
    }