Souf Souf - 5 months ago 37
Java Question

Android google ads error (null reference ?)

I am actually stuck in this error for the last 24h and still can't find solution
the error description:


11-06 18:53:37.745: E/AndroidRuntime(1698): 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


this is some of the xml layout :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background_pattern"
android:orientation="vertical" >
.
.
.
.
.
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="ca-app-pub-xxxxxxx/xxxxxxxx" />

<TextView
android:id="@+id/tv_05"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:textAppearance="?android:attr/textAppearanceMedium" />


</LinearLayout>


oncreate method in mainActivity.java :

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

AdView adview = (AdView) this.findViewById(R.id.adView);

// Request for Ads
AdRequest adRequest = new AdRequest.Builder()

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

adview.loadAd(adRequest);
// Prepare the Interstitial Ad
interstitial = new InterstitialAd(mainActivity.this);
// Insert the Ad Unit ID
interstitial.setAdUnitId(AppConstants.Interstitial_Id);

// Load ads into Interstitial Ads
interstitial.loadAd(adRequest);
.....


i can't see any error in this i checked all imports libraries everything is ok
Please help me I'm running out of time :/

Answer

It is failing because it is not finding an element with id adView in your layout.

Make sure the XML file you displayed above is actually activity_main.xml.

And do a clean build.