Search code examples
androidadmobads

Running Interstitial ad from SliderLayout


I have an Interstitial ad in my application, when i show the ad in onCreate() it works. Now i'm using a library to make image slider with Glide library, i want to display the ad after 20 scrolls of images.

i used a counter to determine the number of images scrolled and then show the ad.

This is the initialize and creation of Interstitial and AdRequest

InterstitialAd interstitial;
AdRequest adRequest;
SliderLayout slider;

int count=0;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_slider);

    slider = findViewById(R.id.slider);
    interstitial = new InterstitialAd(SliderActivity.this);
    interstitial.setAdUnitId(getString(R.string.ad_interisial));
    adRequest = new AdRequest.Builder().addTestDevice("7B7D134FF9931565B8C442934E12A0C1").build();
    interstitial.loadAd(adRequest);
  }

and the slider provides listener for Scrolling pages here is the code i wrote

slider.addOnPageChangeListener(new ViewPagerEx.OnPageChangeListener()   {


        @Override
        public void onPageSelected(int i) {


            count++;
            System.out.println("count = " + count);
            if(count %20 == 0){

                        System.out.println("twenty times");
                        displayInterstitial();


            }


        }
    });

and here is displayInterstitial() method

public void displayInterstitial() { 
    if (interstitial.isLoaded())
    {
        interstitial.show();
    } 
}

When i scrolled 20 images the code prints "twenty times", but the ad not loaded.

Did i miss anything? Why does this problem happen?


Solution

  • interstitial.setAdListener(new AdListener(){
                                public void onAdLoaded(){
                                    System.out.println("adLoaded");
    
                                    interstitial.show();
                                }
                            });
    

    you need to add this listener in onCreate() method. And change the content of method displayInterstitial()like below :

    public void displayInterstitial() { 
        if (!interstitial.isLoaded())
        {
            interstitial.loadAd(adRequest);
        } 
    }