LibGDX ad control tutorial producing null pointer - android

I have been following this tutorial: https://github.com/libgdx/libgdx/wiki/Admob-in-libgdx
I'm sure i have implemented everything correctly and am still getting a null pointer for the handler. Is there something wrong with the code in the tutorial?
Here is my Android Launcher Code:
public class AndroidLauncher extends AndroidApplication implements IActivityRequestHandler{
protected AdView adView;
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;
protected Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch(msg.what) {
case SHOW_ADS:
{
adView.setVisibility(View.VISIBLE);
break;
}
case HIDE_ADS:
{
adView.setVisibility(View.GONE);
break;
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libgdx View
View gameView = initializeForView(new PBGame(this));
// Create and setup the AdMob view
AdView adView = new AdView(this);
adView.setAdUnitId("Secret Key");
adView.setAdSize(AdSize.BANNER);
adView.loadAd(new AdRequest.Builder()
.addTestDevice("Test Device")
.build());
// Add the libgdx view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
adParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
}
#Override
public void showAds(boolean show) {
handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
}
}
My Game Class:
public static final int VIRTUAL_WIDTH = 800;
public static final int VIRTUAL_HEIGHT = 480;
public static final float ASPECT_RATIO =
(float)VIRTUAL_WIDTH/(float)VIRTUAL_HEIGHT;
public static final int zeroMakerX = 400, zeroMakerY = 240;
public static Camera camera;
public static Rectangle viewport;
private IActivityRequestHandler myRequestHandler;
public PBGame(IActivityRequestHandler handler) {
myRequestHandler = handler;
}
#Override
public void create() {
AssetHandler.load();
super.setScreen(new TitleScreen(this));
AssetHandler.music.play();
AssetHandler.music.setLooping(true);
}
#Override
public void dispose() {
super.dispose();
}
}
Finally the ReqestHandler:
public interface IActivityRequestHandler {
public void showAds(boolean show);
}

The problem is as follows:
Your AdView object is defined locally inside the onCreate() function of the AndroidLauncher class. You then attempt to access it outside of onCreate() in the Handler object. The AdView object is out of scope. You should declare the AdView in your AndroidLauncher class outside of onCreate():
AdView adView;
Then in onCreate() you can instantiate it as you did:
// Create and setup the AdMob view
adView = new AdView(this);
adView.setAdUnitId("Secret Key");
adView.setAdSize(AdSize.BANNER);
adView.loadAd(new AdRequest.Builder()
.addTestDevice("Test Device")
.build());

Related

How to show interstitial ad with multiple screens in libgdx?

I successfully implemented banner ad in my libgdx game, now i am trying to implementing interstitial ad. I want to show ad on the button click but the ad is not showing on the screen, i am using log to know if the ad is loading and it is loading everytime but not visible on the screen. i am using multiple screen classes in the game. I have watched several tutorials on it but nothing seems to work.
public class AndroidLauncher extends AndroidApplication implements AdService{
private InterstitialAd interstitialAd;
private ScheduledExecutorService scheduler;
private static final String BANNER_ID = "ca-app-pub-3940256099942544/6300978111";
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
//create a gameView and a bannerAd AdView
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libgdx View
View gameView = initializeForView(new BabyGame(this), config);
// Create and setup the AdMob view
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(BANNER_ID); // Put in your secret key here
AdRequest adRequest = new AdRequest.Builder().addTestDevice("6D0D171A0065AD4E19656B813BC8F493").build();
adView.loadAd(adRequest);
// Add the libgdx view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
adParams.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {}
#Override
public void onAdClosed() {
loadIntersitialAd();
}
});
loadIntersitialAd();
}
private void loadIntersitialAd(){
AdRequest interstitialRequest = new AdRequest.Builder().build();
interstitialAd.loadAd(interstitialRequest);
}
#Override
public void showInterstitial() {
runOnUiThread(new Runnable() {
public void run() {
if (interstitialAd.isLoaded())
interstitialAd.show();
else
loadIntersitialAd();
}
});
}
#Override
public boolean isInterstitialLoaded() {
return interstitialAd.isLoaded();
}
}
This is the BabyGame.java
public class BabyGame extends Game
{
public AdService adService;
BabyGame(AdService ads){
adService = ads;
}
public void create()
{
BabyOrange bp = new BabyOrange(this);
setScreen( bp );
}
}
here is the interface
public interface AdService {
boolean isInterstitialLoaded();
void showInterstitial();
}
I want to show ads here in the BabyOrange.java when the button touched.
public class BabyOrange extends BabyScreen {
private BabyActor bg;
private BabyActor phone;
private ImageButton buttonLeft,buttonRight;
public AdService adService;
private Table table;
private AssetManager asset;
private TextureAtlas atlas;
public BabyOrange(Game g){
super(g);
}
#Override
public void create() {
asset = new AssetManager();
asset.load("background-orange.png",Texture.class);
asset.load("orange-ph.png",Texture.class);
asset.finishLoading();
bg = new BabyActor();
bg.setTexture(asset.get("background-orange.png",Texture.class));
bg.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
ph = new BabyActor();
ph.setTexture(asset.get("orange-ph.png",Texture.class));
ph.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
TextureRegion btLeft = new TextureRegion(new Texture("NUMBEROFF.png"));
Drawable drawableLeft = new TextureRegionDrawable(new TextureRegion(btLeft));
buttonLeft = new ImageButton(drawableLeft);
TextureRegion btRight = new TextureRegion(new Texture("VEHICLEOFF.png"));
Drawable drawableRight = new TextureRegionDrawable(new TextureRegion(btRight));
buttonRight = new ImageButton(drawableRight);
stage.addActor(bg);
stage.addActor(phone);
Gdx.input.setInputProcessor(stage);
buttonRight.addListener(new InputListener(){
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
game.setScreen(new BabyGreen(game));
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
adService.showInterstitial();
}
});
return true;
}
});
buttonLeft.addListener(new InputListener(){
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
game.setScreen(new BabyBlue(game));
return true;
}
});
table = new Table();
table.padLeft(40);
table.setPosition(phone.getWidth()/2,phone.getHeight()/2*0.6f);
table.row().size(stage1.getWidth()/100*20,stage1.getWidth()/100*20);
table.add(buttonLeft);
table.add(buttonCenter);
table.add(buttonRight);
stage.addActor(table);
}
public void dispose(){
bg.getRegion().getTexture().dispose();
phone.getRegion().getTexture().dispose();
stage.dispose();
stage1.dispose();
}
}

Attempt to invoke interface method on a null object reference in libgdx Admob implementation

I am implementing admob banner ad in the libgdx game. I have made several screens and want to show banner ad on each and every screen. I implemented banner ad in the launcher class and trying to show it in the screen class through the interface method calling, but the application is crashing every time with the error.
4-22 20:47:14.466 24246-24280/com.mygdx.game E/AndroidRuntime: FATAL EXCEPTION: GLThread 80476
Process: com.mygdx.game, PID: 24246
java.lang.NullPointerException: Attempt to invoke interface method 'void com.mygdx.game.AdsController.showBannerAd()' on a null object reference
at com.mygdx.game.BabyOrange.create(BabyOrange.java:51)
at com.mygdx.game.BabyScreen.<init>(BabyScreen.java:38)
at com.mygdx.game.BabyOrange.<init>(BabyOrange.java:42)
at com.mygdx.game.BabyGame.create(BabyGame.java:9)
at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:311)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1633)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1354)
Here is the code for the launcher and the screen class
public class BabyOrange extends BabyScreen {
private BabyActor bg;
private BabyActor ph;
private AdsController adsController;
public BabyOrange(Game g,AdsController adsController){
super(g);
this.adsController = adsController;
}
public void create () {
adsController.showBannerAd();
bg = new BabyActor();
bg.setTexture(asset.get("background-orange.png",Texture.class));
bg.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
ph = new BabyActor();
ph.setTexture(asset.get("orange-ph.png",Texture.class));
ph.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
}
Here is the interface
public interface AdsController {
public void showBannerAd();
public void hideBannerAd();
}
And the Android launcher class
public class AndroidLauncher extends AndroidApplication implements AdsController{
private static final String BANNER_ID = "ca-app-pub-959117648XXXXXX/XXXXXXXX";
AdView bannerAd;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
//create a gameView and a bannerAd AdView
View gameView = initializeForView(new BabyGame(), config);
setupAds();
//define the layout
RelativeLayout layout = new RelativeLayout(this);
layout.addView(gameView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layout.addView(bannerAd,params);
setContentView(layout);
}
public void setupAds(){
bannerAd = new AdView(this);
bannerAd.setVisibility(View.INVISIBLE);
bannerAd.setAdUnitId(BANNER_ID);
bannerAd.setAdSize(AdSize.SMART_BANNER);
}
#Override
public void showBannerAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
bannerAd.setVisibility(View.VISIBLE);
AdRequest.Builder builder = new AdRequest.Builder();
AdRequest ad = builder.build();
bannerAd.loadAd(ad);
}
});
}
#Override
public void hideBannerAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
bannerAd.setVisibility(View.INVISIBLE);
}
});
}
}
Your super constructor calls the underlying create function before your adsController is set. Try this code:
public BabyOrange(Game g,AdsController adsController){
super(g);
this.adsController = adsController;
create2();
}
public void create2() {
adsController.showBannerAd();
}
public void create () { // called within super-constructor
bg = new BabyActor();
bg.setTexture(asset.get("background-orange.png",Texture.class));
bg.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
ph = new BabyActor();
ph.setTexture(asset.get("orange-ph.png",Texture.class));
ph.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
}
...

Revmob in Libgdx

Hello I am trying to integrated Banner Ad using RevMob in Libgdx. But it is not displaying for some reason.
I am using the following code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_game_new);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
// cfg.useGL20 = false;
final RelativeLayout gameLayout = new RelativeLayout(this);
RevMobIntegration revmob = new RevMobIntegration(this);
RelativeLayout bannerLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
adParams.addRule(RelativeLayout.CENTER_VERTICAL);
bannerLayout.setLayoutParams(adParams);
game = new MyGdxGame(GameActivity.this, revmob);
game.setRedirectionListener(this);
View gameView = initializeForView(game, cfg);
requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Add the libgdx view
gameLayout.addView(gameView);
// gameLayout.addView(bannerLayout);
Log.d("RevMob", "Checking BannerAd");
if (revmob.getBannerAd() != null) {
Log.d("RevMob", "Displaying Called");
gameLayout.addView(revmob.getBannerAd());
}
// Hook it all up
setContentView(gameLayout);
this.onPause();
this.onResume();
gameLayout.refreshDrawableState();
initChartboost();
// startRevMobSession();
}
Here is the RevMobIntegration class :
public class RevMobIntegration implements RevmobAdInterface {
private static final String APPLICATION_ID = "YourAdmobAppIDHere";
// Set this to false when creating the version for the store.
private static final boolean DEBUG = true;
private RevMobAdsListener listener;
private RevMobFullscreen fullscreenAd;
private RevMobBanner bannerAd;
private Activity application;
private RevMob revmob;
public RevMobIntegration(Activity _application) {
this.application = _application;
startRevMobSession();
}
public void startRevMobSession() {
//RevMob's Start Session method:
revmob = RevMob.startWithListener(application, new RevMobAdsListener() {
#Override
public void onRevMobSessionStarted() {
loadBanner(); // Cache the banner once the session is started
Log.i("RevMob", "Session Started");
}
#Override
public void onRevMobSessionNotStarted(String message) {
//If the session Fails to start, no ads can be displayed.
Log.i("RevMob", "Session Failed to Start");
}
}, application.getString(R.string.rev_mob_app_id));
}
//RevMob
public void loadBanner() {
bannerAd = revmob.preLoadBanner(application, new RevMobAdsListener() {
#Override
public void onRevMobAdReceived() {
showBannerAd(true);
Log.i("RevMob", "Banner Ready to be Displayed"); //At this point,
the banner is ready to be displayed.
}
#Override
public void onRevMobAdNotReceived(String message) {
Log.i("RevMob", "Banner Not Failed to Load");
}
#Override
public void onRevMobAdDisplayed() {
Log.i("RevMob", "Banner Displayed");
}
});
}
#Override
public void showBannerAd(boolean show) {
if(show) {
Log.i("RevMob", "Showing");
if(bannerAd == null) {
startRevMobSession();
} else {
Log.i("RevMob", "Banner Displayed");
bannerAd.show();
}
} else {
bannerAd.hide();
}
}
public RevMobBanner getBannerAd() { return bannerAd; }
}
I have integrated the RevMob in my Activities and it is working fine. But for the Game Screen the ad is initializing but not displaying.
Any suggestions?
It seems revmob.getBannerAd() return null because bannerAd object created when loadBanner(); called. RevMob take some time to start it's session.
if (revmob.getBannerAd() != null) {
Log.d("RevMob", "Displaying Called");
gameLayout.addView(revmob.getBannerAd());
}
You can check this repo for clarification also you can take a look of this class.

Implementing Admob banner when setContentView() is used for the Surfaceview

I am struggling to implement an admob banner into my app because the setContentView() method is used for the surfaceView called gameView so creating the adView in xml cannot be applied to this framework as setContentView is already being used. And I don't know how to do this programmatically. Does anyone have a solution to this?
My main Activity:
public class GameMainActivity extends BaseGameActivity {
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
prefs = getPreferences(Activity.MODE_PRIVATE); // New line!
highScore = retrieveHighScore();
highScoreUnits = retrieveHighScoreUnits();
highScoreTens = retrieveHighScoreTens();
highScoreHundreds = retrieveHighScoreHundreds();
muteButton = retrieveMuteButton();
assets = getAssets();
sGame = new GameView(this, GAME_WIDTH, GAME_HEIGHT);
setContentView(sGame);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
and my custom surfaceView code
public class GameView extends SurfaceView implements Runnable {
private Bitmap gameImage;
private Rect gameImageSrc;
private Rect gameImageDst;
private Canvas gameCanvas;
private Painter graphics;
private Thread gameThread;
private volatile boolean running = false;
private volatile State currentState;
private InputHandler inputHandler;
public GameView(Context context, int gameWidth, int gameHeight) {
super(context);
gameImage = Bitmap.createBitmap(gameWidth, gameHeight,
Bitmap.Config.RGB_565);
gameImageSrc = new Rect(0, 0, gameImage.getWidth(),
gameImage.getHeight());
gameImageDst = new Rect();
gameCanvas = new Canvas(gameImage);
graphics = new Painter(gameCanvas);
SurfaceHolder holder = getHolder();
holder.addCallback(new Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
initInput();
if (currentState == null) {
setCurrentState(new LoadState());
}
initGame();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
pauseGame();
}
});
}
Use a RelativeLayout or a FrameLayout as your parent layout, then just define the layout parameters for the adView to be positioned (for example at the bottom center of the screen like this):
public class GameMainActivity extends BaseGameActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
prefs = getPreferences(Activity.MODE_PRIVATE); // New line!
highScore = retrieveHighScore();
highScoreUnits = retrieveHighScoreUnits();
highScoreTens = retrieveHighScoreTens();
highScoreHundreds = retrieveHighScoreHundreds();
muteButton = retrieveMuteButton();
assets = getAssets();
// Create an ad.
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
// set background color of adview to force it to show
adView.setBackgroundColor(Color.TRANSPARENT);
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
RelativeLayout layout = new RelativeLayout(this);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
// Create an ad request.
AdRequest adRequest = new AdRequest.Builder().build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
// Request full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Create and set your game's view
sGame = new GameView(this, GAME_WIDTH, GAME_HEIGHT);
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
adParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
layout.addView(sGame);
layout.addView(adView, adParams);
setContentView(layout);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}

Admob + Andengine showing ad only on second request

the issue is: the ad doesn't show on first request, but when it makes the second request, it shows right. About 2 seconds before it make the second request, the ad of the first request shows up. Any ideas?
Thanks,
EDIT: I changed the gravity to TOP, and now it shows on the first time, but is showing just the top half of the ad, bizarre, any ideas?
#Override
protected void onSetContentView() {
if(adView != null){
return;
}
final FrameLayout frameLayout = new FrameLayout(this);
final FrameLayout.LayoutParams frameLayoutLayoutParams =
new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT);
final FrameLayout.LayoutParams adViewLayoutParams =
new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT,
Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM);
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(getResources().getString(R.string.ad_unit_id));
adView.setAdListener(new ToastAdListener(this));
adView.loadAd(new AdRequest.Builder().build());
this.mRenderSurfaceView = new RenderSurfaceView(this);
mRenderSurfaceView.setRenderer(mEngine,this);
final android.widget.FrameLayout.LayoutParams surfaceViewLayoutParams =
new FrameLayout.LayoutParams(super.createSurfaceViewLayoutParams());
frameLayout.addView(this.mRenderSurfaceView, surfaceViewLayoutParams);
frameLayout.addView(adView, adViewLayoutParams);
this.setContentView(frameLayout, frameLayoutLayoutParams);
}
#Override
protected void onPause() {
if(adView!=null){
adView.pause();
}
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
if(adView!=null){
adView.resume();
}
}
#Override
protected void onDestroy() {
if(adView!=null){
adView.destroy();
}
super.onDestroy();
}
The problem was solved for me by adding the line
adView.setBackgroundColor(android.graphics.Color.TRANSPARENT);
The way I have done is as follows:
In the method which changes the visibility, I first check is the ad was loaded. If it was not, I don't change the visibility
Set an AdListener for the AdView. in the onReceivedAd(), I check the condition to hide it - if it should be hidden, I hide.
Works fine this way.
I have got the same problem, I solved this way:
Advertisement class:
public class Advertisement {
private AdView adView;
private final Handler adsHandler = new Handler();
public Advertisement(final Activity activity) {
adView = (AdView)activity.findViewById(R.id.adView);
}
//show the ads.
private void showAds () {
adView.loadAd(new AdRequest.Builder().build());
adView.setVisibility(android.view.View.VISIBLE);
adView.setEnabled(true);
}
//hide ads.
private void unshowAds () {
adView.loadAd(new AdRequest.Builder().build());
adView.setVisibility(android.view.View.INVISIBLE);
adView.setEnabled(false);
}
final Runnable unshowAdsRunnable = new Runnable() {
public void run() {
unshowAds();
}
};
final Runnable showAdsRunnable = new Runnable() {
public void run() {
showAds();
}
};
public void showAdvertisement() {
adsHandler.post(showAdsRunnable);
}
public void hideAdvertisement() {
adsHandler.post(unshowAdsRunnable);
}
}
In code:
...
public static Advertisement advertisement = new Advertisement(this);
...
public static void showAd()
{
if (advertisement != null)
advertisement.showAdvertisement();
}
public static void hideAd()
{
if (gangsterAdvertisement != null)
advertisement.hideAdvertisement();
}

Categories

Resources