my app crashes while loading Google Admob ad. It worked fine for a long time but now I get following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.interstitial.InterstitialAd.setFullScreenContentCallback(com.google.android.gms.ads.FullScreenContentCallback)' on a null object reference
I've changed nothing in code, my app is in Play Store and I have the App on my Galaxy S10 & it worked all the time but now if the Ad has to be loaded I get this error. Can somebody help?
Thanks
Edit: Here's my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-93706071examplenumber/4141725063", adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
Log.i("TAG", "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
Log.i("TAG", "onAdLoaded");
mInterstitialAd = null;
}
});
private void showInterstitial(){
if (callbackActive == false){
setCallback();
}
if (mInterstitialAd != null ) {
mInterstitialAd.show(MainActivity.this);
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
}
private void setCallback(){
callbackActive = true;
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdDismissedFullScreenContent() {
Log.d("TAG", "The ad was dismissed.");
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
Log.d("TAG", "The ad failed to show.");
}
#Override
public void onAdShowedFullScreenContent() {
mInterstitialAd = null;
Log.d("TAG", "The ad was shown.");
}
});
}
Put setFullScreenContentCallback in onAdLoaded
here is a code snippet (see code below) and check the full code from AdMob official sample on GitHub
public void loadAd() {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(
this,
AD_UNIT_ID,
adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
MyActivity.this.interstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
Toast.makeText(MyActivity.this, "onAdLoaded()", Toast.LENGTH_SHORT).show();
interstitialAd.setFullScreenContentCallback(
new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
// Make sure to set your reference to null so you don't
// show it a second time.
MyActivity.this.interstitialAd = null;
Log.d("TAG", "The ad was dismissed.");
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
// Make sure to set your reference to null so you don't
// show it a second time.
MyActivity.this.interstitialAd = null;
Log.d("TAG", "The ad failed to show.");
}
#Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
Log.d("TAG", "The ad was shown.");
}
});
}
Related
So i recently updated my code with the latest admob SDK and dependencies.
it is supposed to show an interstitial ad before going to the next page.
upon running it the StartActivity is stuck on process dialog and wont go to the next page.
here is the code
//Start Here
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(StartActivity.this,StartActivity.this.getString(R.string.main_inter), adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
pd.dismiss();
mInterstitialAd = interstitialAd;
mInterstitialAd.show(StartActivity.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
}
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
pd.dismiss();
mInterstitialAd = null;
startActivity(new Intent(StartActivity.this, MainActivity.class));
StartActivity.this.finish();
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
mInterstitialAd = null;
}
#Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
}
#Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
}
});
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
mInterstitialAd = null;
}
});
}
});
}
}
You are not dismissing your progress dialog upon onAdDismissedFullScreenContent
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
pd.dismiss()
mInterstitialAd = null;
StartActivity.this.finish();
}
Always remember to handle dialog states, or it can cause window leaks.
Start Activity before finish() is called
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
pd.dismiss()
mInterstitialAd = null;
startActivity(new Intent(StartActivity.this, NextActivity.class));
StartActivity.this.finish();
}
You should dismiss the dialog if the interstitial fails to load or show.
private void openNextPage(ProgressDialog pd){
pd.dismiss();
mInterstitialAd = null;
startActivity(new Intent(StartActivity.this, MainActivity.class));
StartActivity.this.finish();
}
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(StartActivity.this,
StartActivity.this.getString(R.string.main_inter),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
// Don't dismiss dialog here as we are going to show interstitials now
mInterstitialAd = interstitialAd;
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
}
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
openNextPage(pd);
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
openNextPage(pd);
}
#Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
}
#Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
}
});
mInterstitialAd.show(StartActivity.this);
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
openNextPage(pd);
}
});
I want to set/add a delay when reloading an ad when it has failed to load. I think it could be done with Looper.getMainLooper() but I don´t know how to do this. You can see I have implemented that if the ad fails to load,it will be reloaded up to 5 times, so I think that adding a delay before reloading the ad could be a good option.
Here is my code:
#Override
protected void onResume() {
super.onResume();
requestNewInterstitial(5);
}
private void requestNewInterstitial(int maxRetry) {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
if (maxRetry>0){
/*HERE IS WHERE THE AD IS RELOADED, SO THE DELAY COULD BE SET HERE BEFORE
CALLING THE REQUEST NEW INTERSTITIAL FUNCTION*/
mInterstitialAd = null;
requestNewInterstitial(maxRetry-1);
}
});
}
}
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd != null) {
mInterstitialAd.show(Activityone.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
}
});
I tried to do this.
if (maxRetry>0){
//add a delay before retrying
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestNewInterstitial(maxRetry-1);
}
}, 1000);
}
Hope this fixes your problem.
You can use a simple Handler to delay a function like this:
(Kotlin version, but you get the idea)
private fun reloadInterstitialAd() {
if (maxRetry > 0) {
val delayTime = 5000L // 5 seconds.
val looper = mainLooper // Use `Looper.getMainLooper()` if you do not have access to an Activity context.
mInterstitialAd = null
Handler(looper).postDelayed({
maxRetry--
requestNewInterstitial(maxRetry)
}, delayTime)
} else {
Log.d(TAG, "Max reload reached")
}
}
Use this function like reloadInterstitialAd() in the onAdFailedToLoad callback.
You can use this
Thread.sleep(delay_time_in_milliseconds);
I'm using this code to load and show an interstitial ad. It works fine but as you can see if the ad fails to load onAdFailedToLoad, the interstitial ad is recursively requested. Maybe this could be a really bad practice as if the ad is not loaded, the function could be called a huge number of times. But, I have thought that as I'm requesting the ad after the device is connected to the internet, the probability that the ad is loaded should be almost 100%, but I was just wondering if it is a bad practice to do this. The interstitial ad is shown in the 2 activities, as you can see in one of them, it is shown when a button is clicked and after it is clicked there is an intent to move to another activity. The other activity that the interstitial is shown is almost the same, in this second activity it is shown when the game is paused and also when the level is finished. I don´t know if it is important but all the levels are in the same activity, so the interstitial as I have said is only shown in 2 different activities.
#Override
protected void onResume() {
super.onResume();
CallNewInertial();
}
private void CallNewInertial() {
ConnectionDetector cd = new ConnectionDetector(Activityone.this);
if (cd.isConnectingToInternet()) {
requestNewInterstitial();
}
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
mInterstitialAd = null;
requestNewInterstitial();
}
});
}
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd != null) {
mInterstitialAd.show(Activityone.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
}
});
fixed code to make it perfect:
#Override
protected void onResume() {
super.onResume();
requestNewInterstitial(5);
}
private void requestNewInterstitial(int maxRetry) {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
if (maxRetry>0){
mInterstitialAd = null;
requestNewInterstitial(maxRetry-1);
}
}
});
}
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd != null) {
mInterstitialAd.show(Activityone.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
}
});
(using delay),updated code to make it even more perfect:
#Override
protected void onResume() {
super.onResume();
requestNewInterstitial(5);
}
private void requestNewInterstitial(int maxRetry) {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
if (maxRetry>0){
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
mInterstitialAd = null;
requestNewInterstitial(maxRetry-1);
}
//delay of 10 seconds
}, 10000);
}
});
}
}
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd != null) {
mInterstitialAd.show(Activityone.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
}
});
All I did is to copy code from here
here it is:
public class MainActivity extends AppCompatActivity {
AdRequest adRequest;
RewardedAd mRewardedAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(#NonNull InitializationStatus initializationStatus) {
}
});
adRequest = new AdRequest.Builder().build();
RewardedAd.load(this, "ca-app-pub-3940256099942544/5224354917", adRequest,
new RewardedAdLoadCallback() {
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
super.onAdFailedToLoad(loadAdError);
mRewardedAd = null;
Toast.makeText(MainActivity.this, "VIDEO FAILED TO LOAD", Toast.LENGTH_LONG).show();
Log.d("TFO", loadAdError.toString());
}
#Override
public void onAdLoaded(#NonNull RewardedAd rewardedAd) {
super.onAdLoaded(rewardedAd);
mRewardedAd = rewardedAd;
Toast.makeText(MainActivity.this, "VIDEO LOADED SUCCESSFULLY", Toast.LENGTH_LONG).show();
}
});
}
}
I am using test ad IDs and whenever I compile I get the message VIDEO FAILED TO LOAD which means that the RewardedAd object has not been instantiated.
I'd appreciate your help if you can provide any.
I programmed an app named "Trumple Run" for android. Like the name says it is a Jump & Run game and I want to release it soon. Before that I would like to implement Interstitial Ads from AdMob. I followed the official guide for the implementation of Ads but the app always crashes when I tried to show the add. Here is some code from my MainActivity (info: I cut out code which is not relevant for the issue; the method addzeigen() is called from another class)
public class Main_activity extends Activity {
private InterstitialAd mInterstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //Fullscreen
DisplayMetrics metrics = getResources().getDisplayMetrics(); //Display größe herausfinden
V.Bildbreite = metrics.widthPixels;
V.Bildhöhe = metrics.heightPixels;
addladen();
V.v = new View(this);
setContentView(V.v);
}
public void addladen(){
mInterstitial = new InterstitialAd(this);
mInterstitial.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
AdRequest request = new AdRequest.Builder().build();
mInterstitial.loadAd(request);
}
public void addzeigen(){
if(mInterstitial.isLoaded()){
mInterstitial.show();
addladen();
}
}
I looked at the StackTrace to find the reason for the issue and this two lines indicated that the interstitial is not yet instantiated (returning a null value).
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.android.gms.ads.InterstitialAd.isLoaded()' on a null object reference
Because of that I added a null checker in my addladen() method to prevent a crash.
public void addzeigen(){
if(mInterstitial != null && mInterstitial.isLoaded()){
mInterstitial.show();
addladen();
}
}
But why is my Interstitial object null? Did I not instantiate it in the right way in my addladen() method? I already searched for a long time in the internet but found no solution and asked the AdMob support but they said I should ask here because it is an implementation problem. How do I have to modify my code to make sure that my Interstitial is not null? I would be really happy if you could help me.
create application to when open app, add immidiate load
public class MyApplication extends Application {
public InterstitialAd mInterstitialAd;
private AppOpenManager appOpenAdManager;
private Activity currentActivity;
private int check = 0;
public AdLoader adLoader;
#Override
public void onCreate() {
super.onCreate();
MobileAds.initialize(
this,
new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(
#NonNull InitializationStatus initializationStatus) {
}
});
appOpenAdManager = new AppOpenManager();
loadInterstitial(AD_UNIT_ID_INTERSTITIAL_ADS);
}
public void loadInterstitial(String id) {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(
this,
id,
adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
interstitialAd.setFullScreenContentCallback(
new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
mInterstitialAd = null;
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
// Make sure to set your reference to null so you don't
// show it a second time.
mInterstitialAd = null;
}
#Override
public void onAdShowedFullScreenContent() {
}
});
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
mInterstitialAd = null;
}
});
}
}
then you create class check exception happen when load and open app
public class LoadInterstitialAds {
private static LoadInterstitialAds instance;
private InterstitialAd mInterstitialAd;
public static LoadInterstitialAds getInstance() {
if (instance == null) {
return new LoadInterstitialAds();
}
return instance;
}
public void openAdsThenOpenActivity(Activity activity, InterstitialAdsListener listener) {
Application application = activity.getApplication();
if (application instanceof MyApplication) {
LoadInterstitialAds.this.mInterstitialAd = ((MyApplication) application).mInterstitialAd;
if (LoadInterstitialAds.this.mInterstitialAd != null) {
LoadInterstitialAds.this.mInterstitialAd.show(activity);
LoadInterstitialAds.this.mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
listener.onStartActivity();
((MyApplication) application).loadInterstitial(AD_UNIT_ID_INTERSTITIAL_ADS);
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
((MyApplication) application).loadInterstitial(AD_UNIT_ID_INTERSTITIAL_ADS);
listener.onStartActivity();
}
});
} else {
((MyApplication) application).loadInterstitial(AD_UNIT_ID_INTERSTITIAL_ADS);
listener.onStartActivity();
}
}
}
}
create interface listener tothe convenience of calling
public interface InterstitialAdsListener {
void onStartActivity();
}
and finally, run this code at any where you want to show
LoadInterstitialAds loadInterstitialAds = LoadInterstitialAds.getInstance();
loadInterstitialAds.openAdsThenOpenActivity(getActivity(), ()->{
// your process
});