Spickle
Spickle

Reputation: 47

AdMob makes my app crash on startup?

I'm trying to get admob to work on my app, but everytime I add this code to my MainAcitvity.java:

    AdView mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

the app crashes immediately when I run it. My app is a DrawerLayout with 4 different fragments, each containing it's own ad. I have added the exact same code for the ad as in one of my other apps, on which it works fine.

The logcat says this:

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest)' on a null object reference
        at test.testapp.MainActivity.onCreate(MainActivity.java:110)
        at android.app.Activity.performCreate(Activity.java:6010)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)


at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)

at android.app.ActivityThread.access$800(ActivityThread.java:155)
at      
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)    

Upvotes: 1

Views: 2506

Answers (3)

neronovs
neronovs

Reputation: 526

In my case, I had two same-named layouts: one for the 23th version, another one general. In the first was a block with the R.id.adView in the second it was absented. So, I just deleted the 23th version one and it began working properly

Upvotes: 0

user2902302
user2902302

Reputation: 91

I faced Similar issue. My problem was with single activity. So for my case When i checked closely in resourse file There were two resourse file for my activity:

\res\layout\activity_main_lauch.xml

\res\layout-v21\activity_main_lauch.xml

I was modifing single file, hence it was throwing error. when i apply the change in both files it started working. Hope it might help.

Upvotes: 0

William
William

Reputation: 20196

It is crashing on

mAdView.loadAd(adRequest);

That means that

AdView mAdView = (AdView) findViewById(R.id.adView);

does not find a component with an id of adView in your XML layout.

Make sure you have an AdView with id of adView in your XML layout.

Upvotes: 1

Related Questions