1

I want to add Admob Banner ad with SurfaceView but it gives NullPointerException, Here is code:

private AdView mAdView; private LinearLayout ll; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ll = new LinearLayout(this); mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder() .build(); mAdView.loadAd(adRequest); ll.addView(mAdView); ll.addView(new GamePanel(this)); setContentView(ll); } 

GamePanel is a class that extends SurfaceView and implements SurfaceHolder

Error says:

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 com.example.binnat.zigzag.MainActivity.onCreate(MainActivity.java:54) 

line 52: mAdView.loadAd(adRequest);

1 Answer 1

1

You don't have that view in your layout yet so find the Adview in your LinerLayout.

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

Edit:

You can also move your setContentView call just to after you've created your LinearLayout:

ll = new LinearLayout(this); setContentView(ll); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it helped a lot to find my mistake, actually i created banner ad in xml also. I deleted it from xml and tried with code and it worked

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.