0

I finished my first App, and I wanted to try out to add some ads to it. I tried out the tutorials provided by google, and they work fine. Now, when I try to implement the add in my App I receive the error message: "IllegalStateException: isLoaded must be called on the main UI thread".

So here is what I did in my Main Activity I have the onCreate methods:

public void onCreate(){
    // Create the interstitial.
    interstitial = new InterstitialAd(this);
    interstitial.setAdUnitId(MY_AD_UNIT_ID);

    // Create ad request.
    AdRequest adRequest = new AdRequest.Builder()
    .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
    .addTestDevice("xxxxxxxxxxxxxx")
    .build();

    // Begin loading your interstitial.
    interstitial.loadAd(adRequest);
}

In the same Activity I have:

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

So when I try to call the showInterstitial Method I receive the error described above. I am sitting on this for hours now, and can't find any solution.

1 Answers1

0

I think the below code will be helpful to solve your issue. Use this in your on create function

interstitial.setAdListener(new AdListener() {
    public void onAdLoaded() {
        showInterstitial();
    }
});    

or else you can use the following code & you can test it in a device.

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

interstitial = new InterstitialAd(this);
interstitial.setAdUnitId("***********");

AdRequest adRequest = new AdRequest.Builder().build();
interstitial.loadAd(adRequest);
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
    displayInterstitial();
}
});
}

public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
arunkumar
  • 67
  • 2
  • 10