尝试在ContraintLayout上使用横幅广告时遇到此错误。我在stackoverflow上查找了其他答案,但它们没有解决我的问题。
此代码在不同的布局上对我有用。布局是问题所在,只是不确定是什么原因造成的。
Java:
AdRequest adRequestBanner = new AdRequest.Builder().build();
MobileAds.initialize(this, getString(R.string.admob_app_id));
bannerAd = findViewById(R.id.adView);
bannerAd.loadAd(adRequestBanner);
bannerAd.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
bannerAd.setVisibility(View.VISIBLE);
}
@Override
public void onAdFailedToLoad(int error) {
bannerAd.setVisibility(View.GONE);
}
});
XML:
<android.support.constraint.ConstraintLayout
...
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
</com.google.android.gms.ads.AdView>
</android.support.constraint.ConstraintLayout>
Logcat错误:
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
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.vossendesign.stickerstore.MainActivity1.onCreate(MainActivity1.java:98)
at android.app.Activity.performCreate(Activity.java:7326)
at android.app.Activity.performCreate(Activity.java:7317)