0
  • Whoever downvotes - please explain, I am trying to learn, not an expert programmer and looking for assistance whilst trying to figure what is wrong - downvoting me is not helpful when someone is trying to learn.

In my android project, I have several .java files, one of them being a Global.java file.

What I would like to do, is create a method that I can call simply by using;

Global.showAdmob();

from any of the other java files.

The problem I have is, when I try to create the method inside the Global.java file, it mentions 'cannot use this in a static context'

Here is what I am trying to call from the other files;

    private static InterstitialAd interstitial;

        public static void displayInterstitial1() {
      if (interstitial.isLoaded()) {
        interstitial.show();
      }
    }

    public static void showAdmob() {

        interstitial = new InterstitialAd(this);
        interstitial.setAdUnitId(MY_AD_UNIT_ID);

        AdRequest adRequest = new AdRequest.Builder().build();

        interstitial.loadAd(adRequest);      

        interstitial.setAdListener(new AdListener(){
            public void onAdLoaded(){
                 displayInterstitial1();
            }

            public void onAdClosed(){

            }

            public void onAdFailedToLoad(int errorCode){


            }

  });
    }
E-Riz
  • 31,431
  • 9
  • 97
  • 134
Hypergater
  • 559
  • 1
  • 5
  • 15
  • remove private static from declaring under method. – D.J Sep 19 '16 at 10:45
  • well that might be because `this` doesn´t really make sense in a `static` context. What are you trying to achive by passing `this` to the `InterstitialAd` constructor? what should `this` represent here? – SomeJavaGuy Sep 19 '16 at 10:45
  • http://stackoverflow.com/questions/11664522/why-cant-we-use-this-keyword-in-a-static-method – Laurentiu L. Sep 19 '16 at 10:49
  • @Hypergater it made more sense with the last edit. This one looks confusing and like there is still missing something. – SomeJavaGuy Sep 19 '16 at 10:51
  • You are using keyword **this** in your static code? This is not allowed. But Looks like you Show us not the correct code – Jens Sep 19 '16 at 10:52
  • Changed edit, what I tried was to remove static and use it as a public void, but it would not work that way either – Hypergater Sep 19 '16 at 11:01

1 Answers1

1

might be you have to send context value in your

Global.showAdmob();

like

Global.showAdmob(MainActivity.this);

because Global is not either Activity or fragment class and in your Global you have to make change as

interstitial = new InterstitialAd(context);

Hope it will help you.

Rahul Sharma
  • 12,515
  • 6
  • 21
  • 30