Search code examples
androidlayoutadmob

How can I prevent my app from crashing when using Google AdMob, possibly due to issues with the layout parameters?


I've integrated Google AdMob into my app, but it's causing my app to crash. I suspect that the problem might be related to the layout configuration.

Here's what the issue looks like: AdMob Crash

Here's the relevant code for setting up the AdView and game view:

private AdView createAdView() {
    adView = new AdView(this);
    adView.setAdSize(AdSize.SMART_BANNER);
    adView.setAdUnitId(AD_UNIT_ID_BANNER);
    adView.setId(12345); 
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
    adView.setLayoutParams(params);
    adView.setBackgroundColor(Color.TRANSPARENT);
    return adView;
}

private View createGameView(AndroidApplicationConfiguration cfg) {
    gameView = initializeForView(new SGame(this), cfg);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
    params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
    params.addRule(RelativeLayout.BELOW, adView.getId());
    gameView.setLayoutParams(params);
    return gameView;
}

I suspect that the issue might be related to the layout parameters. Can someone provide guidance on how to prevent the app from crashing when using Google AdMob, especially with regard to layout configuration?

Thank you for your assistance!


Solution

  • Oh, ok. Well, you do have the game view below the ad view. This means it will occupy the region below the ad view and it will be shorter since there's less vertical space for it to occupy. You can probably change: params.addRule(RelativeLayout.BELOW, adView.getId()); to instead align with the parent top.