In my game, I have a class which constructs the Gameview and allows the user to play various levels till he want. Now I want to show an admob interstitial when the level is over. This class GameView.java has method to start the game initially which is invoked from the main activity.
The admob interstitial code requires activity instance as the first argument. So I passed an instance of main activity (using this keyword) to the play method of GameView but I get the following exception on invoking the interstitial code:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
My code in GameView.java is:
InterstitialAd interstitial = new InterstitialAd((MainActivity)mContext,
"admobunitid");
// Create ad request
AdRequest adRequest = new AdRequest();
// Begin loading your interstitial
interstitial.loadAd(adRequest);
interstitial.setAdListener((MainActivity)mContext);
GameView.java doesn't extend any class and doesn't implement any interface as of now. Any help on this?
This is not Activity Class then you need to call within
runOnUiThread
. Like it is android asynctask class doBackground method then you need to call like this.Thanks
This usually happens when you try to show a
Dialog
from outside the Main Thread.Try to wrap that code inside a
Runnable
and then execute it usingMainActivity.runOnUiThread();
You're calling it from a worker thread. You need to call from within the main thread. You could use a handler, for example.
Are there any contraindications of using interfaces? Because using them in this case would be resonable.