Implementing an interstitial ad after a number of interactions

Greetings! (I hope this is the most appropriate section to post this thread)

I’m making an app that simply involves button presses, it’s a “how-to” app. Very simple.
However, I do not have any natural breaks in my app; so I wish to implement an interstitial ad after a certain number of button-presses/interactions.

Now, I’m not much of a coding guy, I made it this far in my app by researching and taking snippets of code and putting it all together (I’m learning a lot though).

But being able to implement an interstitial after “X” number of interactions/button-presses is quite possibly the only barrier that I just cannot find a code for. I’m using AdMob in Eclipse if it makes a difference.
I’ve done tons of research on google, I’ve tried making threads on websites such as stackoverflow, I’ve even searched around as much as I could on my college campus to help me out. But no luck. I’m really stuck at a roadblock here on how to code this.

If anyone has any advice, it would be greatly appreciated! Thank you!

Hi!

This is pretty simple if all these button events are happening in the same activity.

Just put an int at the top of your code. Every time a button is clicked you increase the int by one and then do a check if you should show the ad or not.

Example:

int counter = 0;

public void Onclick(View v)
{
counter++;
showAd();
}
public void Onclick2(View v)
{
counter++;
showAd();
}

private void showAd()
{
if(counter>=5)
{
//show the ad
counter = 0;
}
}

Now, I haven’t tested that code at all - so don’t just go copy-paste it. Try to understand the logic.

Hope it helps.

Thank you SocioSoft for the reply!

I’ve been quiet because I’ve been playing around with your code and learning for a few days trying to understand how I can make it fit in haha

I’m really happy that I’m on the right track now! Before I was just babbling in the dark, but now I definitely have a direction to move and I deeply appreciate this advice!

I see that the code works in a way that it starts at zero, once the view is clicked it adds +1 because of the counter++ and goes through the loop. If it is less than 5 it goes back through the loop until it reaches the number 5 or greater and THEN it will display the ad and become the number zero. Definitely something I need!

However, the problem I’m having is that it still is sending me interstitial ads on each click so I’m trying to see what part of my code is making this happen

Things I have tried:

  • putting interstitial.show() after your “//show the ad” note
  • deleting parts of my code and putting them after your “//show the ad” note hoping that the reason why the ads keep popping up is because my code may call for the ad a second time making the counter become void
  • changing the code from public and private
  • putting the counter in other places of the code for grins (though it makes tons more sense to keep in the beginning than somewhere in the middle)
  • putting the displayInterstitial() void lines of code after the //show ad part of the counter

However still no luck =/

Here is my (very simple) code if it makes things easier

(I am still working on the code, so I’ll be constantly editing this as time goes on)
Right now: The code shows banner and interstitial ads each time (I feel like this happens because of the bottom of the code where it calls for the itnerstitial.show(), I’ll have to work on it tomorrow)
Goal: Show banner ads each time, however have the interstitial show every 5 times

public class Commonproblem1class extends Activity {
private InterstitialAd interstitial;

int counter = 0;

public void Onclick(View v)
{
counter++;
showAd();
}
public void Onclick2(View v)
{
counter++;
showAd();
}

private void showAd()
{
if(counter>=5)
;
{
//show the ad
interstitial.show();
counter = 0;
}
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Get the view from xml
setContentView(R.layout.commonproblem1);

//Prepare the Interstitial Ad
interstitial = new InterstitialAd(Commonproblem1class.this);

//Insert the Ad Unit ID
interstitial.setAdUnitId(“ca-app-pub-XXXXXXX/XXXXXXXX”);

//Locate the Banner Ad in xml
AdView adView = (AdView) this.findViewById(R.id.adView);

//Request for Ads
AdRequest adRequest = new AdRequest.Builder()

//Add a test device to show Test Ads
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();

//Load ads into Banner Ads
adView.loadAd(adRequest);

//Load ads into Interstitial Ads
interstitial.loadAd(adRequest);

//Prepare an Interstitial Ad Listener
interstitial.setAdListener(new AdListener() {

public void onAdLoaded() {
//Call displayInterstitial() function
displayInterstitial();
}
});
}

public void displayInterstitial() {
//If Ads are loaded, show Interstitial else show nothing.
if (interstitial.isLoaded()) {
interstitial.show();
}
}
}

Again, thank you for the advice! I really really appreciate this direction you have given me! It’s awesome!

I’ll be doing more testing and updating on what I’m trying after I post this; I’ll still be working with this project and hopefully figure out what’s going on

Hi,

Don’t have much time at the moment but I think I found your problem. At the bottom of your OnCreate Method you are setting up the adListener with the OnAdLoaded event for the interstitial and then showing it. This means that you will show the ad as soon as it is done loading… Obviously not what you want.

Also, make sure to bind your Button’s events to the OnClick events that I created.

Anyway, here is the modified code. Hope it helps"

public class Commonproblem1class extends Activity
{
private InterstitialAd interstitial;
private int counter = 0;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

  // Get the view from xml
  setContentView(R.layout.commonproblem1);
  // Prepare the Interstitial Ad
  interstitial = new InterstitialAd(Commonproblem1class.this);
  // Insert the Ad Unit ID
  interstitial.setAdUnitId("ca-app-pub-XXXXXXX/XXXXXXXX");
  // Locate the Banner Ad in xml
  AdView adView = (AdView) this.findViewById(R.id.adView);
  // Request for Ads
  AdRequest adRequest = new AdRequest.Builder()
  // Add a test device to show Test Ads
  .addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
  // Load ads into Banner Ads
  adView.loadAd(adRequest);
  // Load ads into Interstitial Ads
  loadInterstitial();

}

public void Onclick(View v)
{
//Adds to the counter every time a button is clicked.
//Remember to bind your buttons to this event!
counter++;
displayInterstitial();
}

public void Onclick2(View v)
{
//Adds to the counter every time a button is clicked.
//Remember to bind your buttons to this event!
counter++;
displayInterstitial();
}

private void displayInterstitial()
{
// If Ads are loaded and counter >= 5 show Interstitial, else show nothing.
if (interstitial.isLoaded() & counter>=5)
{
//Resets the counter
counter = 0;
//Shows the ad
interstitial.show();
//Loads a new one
loadInterstitial();
}
}

private void loadInterstitial()
{
AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
interstitial.loadAd(adRequest);
}
}

Again, thank you so much man! I feel like I’m just about there! Definitely learning a lot here, the code makes a lot more sense haha

Here’s my final code, eclipse does not show me errors, however the app crashes when I reach the page I would like to put ads on
I totally feel like I’m super close though!

My best guess are the brackets ending the 2nd OnClick, I made a bolded note of it in the code (also a mental note for me as well), or perhaps it’s because I’ve overriden the onclick?
I’ll be doing some more debugging later on tonight, thanks so much again!

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;

public class Commonproblem1class extends Activity
{
private InterstitialAd interstitial;
private int counter = 0;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

//Get the view from xml
setContentView(R.layout.commonproblem1);

//Prepare the Interstitial Ad
interstitial = new InterstitialAd(Commonproblem1class.this);

//Insert the Ad Unit ID
interstitial.setAdUnitId(“ca-app-pub-XXXXXX/XXXXXXX”);

//Locate the Banner Ad in xml
AdView adView = (AdView) this.findViewById(R.id.adView);

//Request for Ads
AdRequest adRequest = new AdRequest.Builder()

//Add a test device to show Test Ads
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(“XXXXXXXXXXXXX”)
.build ();

//Load ads into Banner Ads
adView.loadAd(adRequest);

//Load ads into Interstitial Ads
loadInterstitial();

[b]final Button button = (Button) findViewById(R.id.commonproblems1);

//LINE 50
button.setOnClickListener(new View.OnClickListener() {[/b]

@Override
public void onClick(View v) {

//Adds to the counter every time a button is clicked.
//Remember to bind your buttons to this event!

counter++;
displayInterstitial();
}
});

final Button button1 = (Button) findViewById(R.id.commonproblems2);
button1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

//Adds to the counter every time a button is clicked.
//Remember to bind your buttons to this event!
counter++;
displayInterstitial();
}});
}
// These brackets may be the problem, however eclipse forces me to put brackets here

private void displayInterstitial()
{
// If Ads are loaded and counter >= 5 show Interstitial, else show nothing.
if (interstitial.isLoaded() & counter>=5)
{
//Resets the counter
counter = 0;
//Shows the ad
interstitial.show();
//Loads a new one
loadInterstitial();
}
}

private void loadInterstitial()
{
AdRequest adRequest = new AdRequest.Builder().
addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(“XXXXXXXXXXX”)
.build();
interstitial.loadAd(adRequest);
}
}

Hello,

It’s not the brackets. Brackets, syntax, typo’s etc are compile-time errors. They will give you an error before you can build or run the app. When you open the app and it then crashes, you experienced a run-time error. These are usually logic errors, but can happen for a lot of reasons.

For run-time errors, check your android log (logcat) after you experience the error. It should pop up a red error message that tells you exactly what went wrong, where.

Ok!

The red messages from the logcat I’ve put into bold.

It’s a little overwhelming, but my best guess is there’s something “null” about the onclicklistener method I’ve made?
And the problem is at line 50?
line 50 of the previous code is: button.setOnClickListener(new View.OnClickListener() {

For the case if I’m right that it is the onClick, I’ve tried:

  • “implements View.OnClickListener” after the extends part of the class
  • changed (View v) to (View view)
  • I’ve noticed that OnClickListener was not “imported” so I tried throwing it into the imports, but eclipse recognized it as an unkown import
  • Tried some “onclick” thing in xml and threw it over to the java, no luck though

I’ll see what more I can experiment on tomorrow

01-23 00:46:26.973: D/dalvikvm(19087): GC_FOR_ALLOC freed 131K, 9% free 8366K/9119K, paused 27ms, total 28ms
01-23 00:46:26.980: I/dalvikvm-heap(19087): Grow heap (frag case) to 12.447MB for 4410016-byte allocation
01-23 00:46:27.019: D/dalvikvm(19087): GC_CONCURRENT freed 1K, 6% free 12672K/13475K, paused 12ms+2ms, total 42ms
01-23 00:46:30.098: D/libEGL(19087): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
01-23 00:46:31.379: D/libEGL(19087): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
01-23 00:46:31.394: D/libEGL(19087): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
01-23 00:46:32.121: D/OpenGLRenderer(19087): Enabling debug mode 0
01-23 00:46:32.316: I/Choreographer(19087): Skipped 295 frames! The application may be doing too much work on its main thread.
01-23 00:46:39.504: D/dalvikvm(19087): GC_FOR_ALLOC freed 42K, 6% free 12801K/13475K, paused 22ms, total 25ms
01-23 00:46:39.551: I/dalvikvm-heap(19087): Grow heap (frag case) to 16.778MB for 4410016-byte allocation
01-23 00:46:39.590: D/dalvikvm(19087): GC_CONCURRENT freed 12K, 5% free 17095K/17827K, paused 23ms+2ms, total 46ms
01-23 00:46:47.558: I/dalvikvm(19087): Could not find method android.webkit.WebSettings.getDefaultUserAgent, referenced from method com.google.android.gms.ads.internal.util.g.a
01-23 00:46:47.558: W/dalvikvm(19087): VFY: unable to resolve static method 3091: Landroid/webkit/WebSettings;.getDefaultUserAgent (Landroid/content/Context;)Ljava/lang/String;
01-23 00:46:47.558: D/dalvikvm(19087): VFY: replacing opcode 0x71 at 0x0011
01-23 00:46:48.160: I/dalvikvm(19087): Total arena pages for JIT: 11
01-23 00:46:48.160: I/dalvikvm(19087): Total arena pages for JIT: 12
01-23 00:46:48.160: I/dalvikvm(19087): Total arena pages for JIT: 13
01-23 00:46:48.160: I/dalvikvm(19087): Total arena pages for JIT: 14
01-23 00:46:48.168: I/dalvikvm(19087): Total arena pages for JIT: 15
01-23 00:46:48.168: I/dalvikvm(19087): Total arena pages for JIT: 16
01-23 00:46:48.168: I/dalvikvm(19087): Total arena pages for JIT: 17
01-23 00:46:48.191: I/dalvikvm(19087): Total arena pages for JIT: 18
01-23 00:46:48.551: D/dalvikvm(19087): DexOpt: — BEGIN ‘ads524102128.jar’ (bootstrap=0) —
01-23 00:46:52.762: I/Ads(19087): Starting ad request.
01-23 00:46:53.371: I/Ads(19087): Please set theme of AdActivity to @android:style/Theme.Translucent to enable transparent background interstitial ad.
01-23 00:46:53.410: I/Ads(19087): Starting ad request.
01-23 00:46:53.473: I/Ads(19087): Please set theme of AdActivity to @android:style/Theme.Translucent to enable transparent background interstitial ad.
01-23 00:46:53.832: D/AndroidRuntime(19087): Shutting down VM
01-23 00:46:53.832: W/dalvikvm(19087): threadid=1: thread exiting with uncaught exception (group=0x40e5c2a0)
[b]01-23 00:46:54.137: E/AndroidRuntime(19087): FATAL EXCEPTION: main
01-23 00:46:54.137: E/AndroidRuntime(19087): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxxxxxx.xxxxxxx/com.xxxx.xxxxx.Commonproblem1class}: java.lang.NullPointerException
01-23 00:46:54.137: E/AndroidRuntime(19087): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2136)
01-23 00:46:54.137: E/AndroidRuntime(19087): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2174)
01-23 00:46:54.137: E/AndroidRuntime(19087): at android.app.ActivityThread.access$700(ActivityThread.java:141)
01-23 00:46:54.137: E/AndroidRuntime(19087): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1267)
01-23 00:46:54.137: E/AndroidRuntime(19087): at android.os.Handler.dispatchMessage(Handler.java:99)
01-23 00:46:54.137: E/AndroidRuntime(19087): at android.os.Looper.loop(Looper.java:137)
01-23 00:46:54.137: E/AndroidRuntime(19087): at android.app.ActivityThread.main(ActivityThread.java:5059)
01-23 00:46:54.137: E/AndroidRuntime(19087): at java.lang.reflect.Method.invokeNative(Native Method)
01-23 00:46:54.137: E/AndroidRuntime(19087): at java.lang.reflect.Method.invoke(Method.java:511)
01-23 00:46:54.137: E/AndroidRuntime(19087): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
01-23 00:46:54.137: E/AndroidRuntime(19087): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
01-23 00:46:54.137: E/AndroidRuntime(19087): at dalvik.system.NativeStart.main(Native Method)
01-23 00:46:54.137: E/AndroidRuntime(19087): Caused by: java.lang.NullPointerException

01-23 00:46:54.137: E/AndroidRuntime(19087): at com.xxxx.xxxxxx.Commonproblem1class.onCreate(Commonproblem1class.java:50)

01-23 00:46:54.137: E/AndroidRuntime(19087): at android.app.Activity.performCreate(Activity.java:5058)
01-23 00:46:54.137: E/AndroidRuntime(19087): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
01-23 00:46:54.137: E/AndroidRuntime(19087): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
01-23 00:46:54.137: E/AndroidRuntime(19087): … 11 more[/b]
01-23 00:46:54.160: D/dalvikvm(19087): DexOpt: — END ‘ads524102128.jar’ (success) —
01-23 00:46:54.238: D/dalvikvm(19087): DEX prep ‘/data/data/com.xxxxx.xxxxxx/cache/ads524102128.jar’: unzip in 0ms, rewrite 5610ms
01-23 00:46:55.004: D/dalvikvm(19087): GC_CONCURRENT freed 833K, 5% free 19168K/20131K, paused 15ms+16ms, total 69ms
01-23 00:46:58.965: I/Process(19087): Sending signal. PID: 19087 SIG: 9
01-23 00:46:59.660: E/Trace(19313): error opening trace file: No such file or directory (2)
01-23 00:47:00.324: D/dalvikvm(19313): GC_FOR_ALLOC freed 127K, 9% free 8367K/9119K, paused 53ms, total 53ms
01-23 00:47:00.340: I/dalvikvm-heap(19313): Grow heap (frag case) to 12.448MB for 4410016-byte allocation
01-23 00:47:00.387: D/dalvikvm(19313): GC_CONCURRENT freed 1K, 6% free 12672K/13475K, paused 21ms+2ms, total 52ms

Hello,

Yes - it means something is null on line 50. Most likely that the button you are trying to set that onclick on is null. Ensure that the .findViewById is finding the button.
Why don’t you debug and put a breakpoint on line 50? That way you can see if it is null before that onclick is set.

Regards
SocioSoft

Thank you for the reply again SocioSoft!

After putting a breakpoint on line 50 of the code, the code ran smoothly. I clicked “step over” a bunch of times and started to get tabs popping up such as “Activity Thread” and “Zygoteinit”.

The code started to error after I “stepped over” the bolded line below in ThreadGroup.java (I didn’t make this class, most likely something that is packaged when you make an application"

public void uncaughtException(Thread t, Throwable e) {
    if (parent != null) {

parent.uncaughtException(t, e);

So i want to say what happened was that one line of code (line 50) went through everything until it reached the null check of the application? I want to say the onclick is null, but I’m not sure how I can prove it.


The thing is that this error doesn’t make much sense to me, I’ve used this code in my Main Activity, where I link my buttons to certain pages. This code was the exact code I used in the Main Activity java code and it works well.

Button button = (Button) findViewById(R.id.commonproblems1);
button.setOnClickListener(new View.OnClickListener() {

However, it does not work for the interstitial ads?


Here is what I have currently if you’re curious at all (I switched a few things around (just want to get one button working properly, then I’ll add more), still the same logcat error though). Also, if it matters, my code runs smoothly if I change it to this example: http://www.androidbegin.com/tutorial/integrating-new-google-admob-banner-interstitial-ads/ (though it does not include counters).

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;

public class Commonproblem1class extends Activity
{
private InterstitialAd interstitial;
private int counter = 0;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

//Get the view from xml
setContentView(R.layout.commonproblem1);

//Prepare the Interstitial Ad
interstitial = new InterstitialAd(Commonproblem1class.this);

//Insert the Ad Unit ID
interstitial.setAdUnitId(“ca-app-pub-xxxxxx/xxxxxxx”);

//Locate the Banner Ad in xml
AdView adView = (AdView) this.findViewById(R.id.adView);

//Request for Ads
AdRequest adRequest = new AdRequest.Builder()

//Add a test device to show Test Ads
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(“xxxxxxxxxxxx”)
.build ();

//Load ads into Banner Ads
adView.loadAd(adRequest);

//Load ads into Interstitial Ads
loadInterstitial();

Button button = (Button) findViewById(R.id.commonproblems1);
button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Adds to the counter every time a button is clicked.
//Remember to bind your buttons to this event!

  	counter++;
  	displayInterstitial();

}
});};

private void displayInterstitial()
{
// If Ads are loaded and counter >= 5 show Interstitial, else show nothing.
if (interstitial.isLoaded() & counter>=5)
{
//Resets the counter
counter = 0;
//Shows the ad
interstitial.show();
//Loads a new one
loadInterstitial();
}
}

private void loadInterstitial()
{
AdRequest adRequest = new AdRequest.Builder().
addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(“xxxxxxxxxxxx”)
.build();
interstitial.loadAd(adRequest);
}

}

Thank you again, I really appreciate the help!

I’ll try to spend the night working as much as I can on it, it’s making me very flustered though

Don’t bother with the debugging, especially in such a simple case like here… Why take a nuclear bomb to kill a fly? Yeah, you’ll probably kill it, but you could do it with your hand or with fly swatter. Same here, why you debug android code written by google, looking for some highly unlikely error by Google team, while the “button” is null on line 50.
After line 49:
Button button = (Button) findViewById(R.id.commonproblems1);
you could just write:
System.out.println("this is my button: " + button);
System.out.println("is my button null at the moment? " + button == null);
And then check what is there in the log.
Are you sure that commonproblem1.xml has a button with id commonproblems1 ?

What allagainstyou is saying is correct. Most likely cause is that the button you are trying to reference is not present in the layout.xml file. I suggested debugging, because this is a core development skill that you absolutely must have, in the hopes that you could understand what was going wrong on your own. Software development is not only about knowing code, but understanding it.

But yes, you can’t get past that line because it is throwing the null exception.

I guess its pointless to argue too much about it… In most simple cases, I think its much faster to log and check the logs just before the stacktrace, than to connect with debug. I debug only when I face a really complicated issue, for example while implementing metaheuristics or while dealing with complicated data structures… but everyone has his own preferences. Anyway, according to thread creator’s code, in res/layout folder there should be commonproblem1.xml, and inside it you need a button with “@+id/commonproblems1”.

oh my god I am such an idiot

I had swore that my button id’s were correct. What I did was I had the button id in the “common problems menu” page and I was hosting the ad in the “common problems 1” page, the xml for the button id was found in the “common problems menu” not the “common problems 1” page. wow.
I thought that I could call upon buttons that were in my project (which would be really cool if I was able to do that, but I’ve aksed enough questions for now haha), but what happened was I needed the button in the actual xml that the java class was hooked up to; man I feel so dumb. Everything works now!

Thank you allagainstyou and a huge thanks to you SocioSoft for being incrediby patient with me and my kiddie code, I wish there was a way I can repay you rather than “thanks” all the time haha.

Definitely a healthy learning experience with a side of dumb hahah
And now I know how debugging works! woo

Thank you so much again guys!

https://www.google.com.pk/?gws_rd=cr,ssl&ei=H9jHVIfsHMG8ygP89YHACg#q=money+making+forum