Issue
Firstly, sorry for my bad English.
When I build apk and try opening apk in my phone, it gives apk has stoped working. The ad unit ID must be set on InterstitialAd before loadAd is called
Error.
What am I doing wrong? Thanks.
public class MainActivity extends AppCompatActivity {
private AdView mAdView;
private InterstitialAd mInterstitialAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
MobileAds.initialize(this, "ca-app-pub-9823610014389662~4002090629");
mInterstitialAd = new InterstitialAd(MainActivity.this);
mInterstitialAd.setAdUnitId("ca-app-pub-9823610014389662/2024107626");
mInterstitialAd.loadAd(adRequest);
mInterstitialAd.setAdListener(new AdListener() {
public void onAdLoaded() {
displayInterstitial();
}
});
}
public void displayInterstitial() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
Solution
If logcat
is pointing that the problem is arising only because of Interstitial ads then try this:
Much simpler & tested way - which fills ad request 95-98% times
InterstitialAd interstitialAd = null;
Then put it inside onCreate()
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(getString(R.string.your_interstitial_string_name);
AdRequest adRequest = new AdRequest.Builder().build();
interstitialAd.loadAd(adRequest);
I prefer calling it onBackPressed()
, you can fit it to your requirement.
@Override
public void onBackPressed() {
if (interstitialAd.isLoaded()) {
interstitialAd.show();
interstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
super.onAdClosed();
finish();
}
});
} else {
super.onBackPressed();
}
}
Also, don't forget to put String Values in your strings.xml
file
<string name="your_interstitial_string_name">ca-app-pub-9823610014389662/2024107626</string>
Answered By - Rohit Sharma
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.