I'm having trouble showing interstitial adds on a natural breaking point in my game. For now I'm able to load and show these interstitial adds, even when I'm changing activities.
My main problem is that I can't decide myself when these adds will show.
I use OpenGl ES and use the badlogic framework. Therefore the mainactivity is called each time over and over when I switch screens.
This is what I created now, by using my shared preferences and a little helper class I'm able to trace in which stage the add is.
public abstract class GLGame extends Activity implements Game, Renderer {
enum GLGameState {
....
}
GLSurfaceView glView;
GLGraphics glGraphics;
....
public InterstitialAd interstitial;
private static final String AD_UNIT_ID = "****";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
glView = new GLSurfaceView(this);
glView.setRenderer(this);
setContentView(glView);
glGraphics = new GLGraphics(glView);
....
// my shared pref is set to 0 when add is not loaded
if (addcheck.showadd(getApplicationContext())==0){
interstitial = new InterstitialAd(getApplicationContext());
interstitial.setAdUnitId(AD_UNIT_ID);
// Create ad request.
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("****")
.build();
// Begin loading your interstitial.
// I set my shared pref to 1 to tell the add is loaded, for later use in the game
interstitial.loadAd(adRequest);
interstitial.setAdListener(new AdListener(){
public void onAdLoaded(){
addcheck.setadd(1,getApplicationContext());
}});
}
// Somewhere in my game I set the pref to 2, where I want to show the add.
if (addcheck.showadd(getApplicationContext())==2&interstitial.isLoaded()){
displayInterstitial();
// after showing the add, I put my pref back to 1, so I it wont show later
addcheck.setadd(1,getApplicationContext());
}
}
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
In my case, I will call displayInterstitial from out the same mainactivity, however this mainactivity is re-loaded a few more times. I think the interstitial is not valid anymore cause I'm getting nullpointer error on interstitial.isLoaded()
Here is some logcat output, which is not my main problem.
07-13 21:49:53.009: E/AndroidRuntime(29230): FATAL EXCEPTION: main
07-13 21:49:53.009: E/AndroidRuntime(29230): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.badlogic.androidgames.glbasics/com.glbasics.MainScreen}: java.lang.NullPointerException
07-13 21:49:53.009: E/AndroidRuntime(29230): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
07-13 21:49:53.009: E/AndroidRuntime(29230): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
Someone knows how to show these loaded adds when I want to? The preferences was just an idea I was playing with.