希望您一切都好。我想在单击按钮上显示插页式广告,但是我为插页式广告建立了一个单独的类,并在此类中创建了一种方法。它访问插页广告类的方法并显示广告,但是当我单击按钮时,它给我插页广告类中的错误。我在这一小错误上停留了一天,但我无法解决。我希望你们能给我更好的答复。
SplashScreen
package com.deitel.adsmobapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.NativeExpressAdView;
public class SplashScreen extends AppCompatActivity {
private AdView mAdview;
Button btn_move;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
btn_move=findViewById(R.id.btn_move);
btn_move.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Interstitial interstitial=new Interstitial();
interstitial.prepareAd();
Intent i=new Intent(SplashScreen.this,MainActivity.class);
startActivity(i);
}
});
/*Banner Ads*/
MobileAds.initialize(this,"ca-app-pub-3940256099942544~3347511713");
mAdview=findViewById(R.id.adView);
AdRequest adRequest=new AdRequest.Builder().build();
mAdview.loadAd(adRequest);
}
@Override
protected void onPause() {
super.onPause();
finish();
}
}
Interstiatil类
package com.deitel.adsmobapp;
import android.app.Activity;
import android.app.Application;
import android.util.Log;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
public class Interstitial extends Application {
private InterstitialAd interstitialAd;
@Override
public void onCreate() {
super.onCreate();
SplashScreen splashScreen=new SplashScreen();
interstitialAd = new InterstitialAd(splashScreen);
interstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
AdRequest adRequest=new AdRequest.Builder().build();
interstitialAd.loadAd(adRequest);
prepareAd();
}
public void prepareAd() {
if (interstitialAd.isLoaded())
{
interstitialAd.show();
}
else
{
Log.d("tag","Ads is not loaded");
}
}
}
错误
01-06 17:05:51.907 7044-7044/com.deitel.adsmobapp E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.deitel.adsmobapp.Interstitial.prepareAd(Interstitial.java:26)
at com.deitel.adsmobapp.SplashScreen$1.onClick(SplashScreen.java:31)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.dispatchMessage(Handler.java:92)
错误是Interstiatil类im方法prepareAd()的第26行中的NPE。interstitialAd为null,因为它是在创建活动时调用的onCreate()中初始化的。您应该将类更改为从Activity继承,而不是从Application继承。并且不要在onClick方法中调用prepareAd()。
public class Interstitial extends Activity