Why can't I instantiate a rewarded ad using the following code? - java

All I did is to copy code from here
here it is:
public class MainActivity extends AppCompatActivity {
AdRequest adRequest;
RewardedAd mRewardedAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(#NonNull InitializationStatus initializationStatus) {
}
});
adRequest = new AdRequest.Builder().build();
RewardedAd.load(this, "ca-app-pub-3940256099942544/5224354917", adRequest,
new RewardedAdLoadCallback() {
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
super.onAdFailedToLoad(loadAdError);
mRewardedAd = null;
Toast.makeText(MainActivity.this, "VIDEO FAILED TO LOAD", Toast.LENGTH_LONG).show();
Log.d("TFO", loadAdError.toString());
}
#Override
public void onAdLoaded(#NonNull RewardedAd rewardedAd) {
super.onAdLoaded(rewardedAd);
mRewardedAd = rewardedAd;
Toast.makeText(MainActivity.this, "VIDEO LOADED SUCCESSFULLY", Toast.LENGTH_LONG).show();
}
});
}
}
I am using test ad IDs and whenever I compile I get the message VIDEO FAILED TO LOAD which means that the RewardedAd object has not been instantiated.
I'd appreciate your help if you can provide any.

Related

Activity is stuck on process dialog and wont go to the next page

So i recently updated my code with the latest admob SDK and dependencies.
it is supposed to show an interstitial ad before going to the next page.
upon running it the StartActivity is stuck on process dialog and wont go to the next page.
here is the code
//Start Here
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(StartActivity.this,StartActivity.this.getString(R.string.main_inter), adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
pd.dismiss();
mInterstitialAd = interstitialAd;
mInterstitialAd.show(StartActivity.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
}
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
pd.dismiss();
mInterstitialAd = null;
startActivity(new Intent(StartActivity.this, MainActivity.class));
StartActivity.this.finish();
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
mInterstitialAd = null;
}
#Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
}
#Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
}
});
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
mInterstitialAd = null;
}
});
}
});
}
}
You are not dismissing your progress dialog upon onAdDismissedFullScreenContent
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
pd.dismiss()
mInterstitialAd = null;
StartActivity.this.finish();
}
Always remember to handle dialog states, or it can cause window leaks.
Start Activity before finish() is called
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
pd.dismiss()
mInterstitialAd = null;
startActivity(new Intent(StartActivity.this, NextActivity.class));
StartActivity.this.finish();
}
You should dismiss the dialog if the interstitial fails to load or show.
private void openNextPage(ProgressDialog pd){
pd.dismiss();
mInterstitialAd = null;
startActivity(new Intent(StartActivity.this, MainActivity.class));
StartActivity.this.finish();
}
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(StartActivity.this,
StartActivity.this.getString(R.string.main_inter),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
// Don't dismiss dialog here as we are going to show interstitials now
mInterstitialAd = interstitialAd;
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
}
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
openNextPage(pd);
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
openNextPage(pd);
}
#Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
}
#Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
}
});
mInterstitialAd.show(StartActivity.this);
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
openNextPage(pd);
}
});

Is it a good practice to use recursion to reload an ad using Admob if it fails when it is loaded?

I'm using this code to load and show an interstitial ad. It works fine but as you can see if the ad fails to load onAdFailedToLoad, the interstitial ad is recursively requested. Maybe this could be a really bad practice as if the ad is not loaded, the function could be called a huge number of times. But, I have thought that as I'm requesting the ad after the device is connected to the internet, the probability that the ad is loaded should be almost 100%, but I was just wondering if it is a bad practice to do this. The interstitial ad is shown in the 2 activities, as you can see in one of them, it is shown when a button is clicked and after it is clicked there is an intent to move to another activity. The other activity that the interstitial is shown is almost the same, in this second activity it is shown when the game is paused and also when the level is finished. I don´t know if it is important but all the levels are in the same activity, so the interstitial as I have said is only shown in 2 different activities.
#Override
protected void onResume() {
super.onResume();
CallNewInertial();
}
private void CallNewInertial() {
ConnectionDetector cd = new ConnectionDetector(Activityone.this);
if (cd.isConnectingToInternet()) {
requestNewInterstitial();
}
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
mInterstitialAd = null;
requestNewInterstitial();
}
});
}
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd != null) {
mInterstitialAd.show(Activityone.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
}
});
fixed code to make it perfect:
#Override
protected void onResume() {
super.onResume();
requestNewInterstitial(5);
}
private void requestNewInterstitial(int maxRetry) {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
if (maxRetry>0){
mInterstitialAd = null;
requestNewInterstitial(maxRetry-1);
}
}
});
}
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd != null) {
mInterstitialAd.show(Activityone.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
}
});
(using delay),updated code to make it even more perfect:
#Override
protected void onResume() {
super.onResume();
requestNewInterstitial(5);
}
private void requestNewInterstitial(int maxRetry) {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
if (maxRetry>0){
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
mInterstitialAd = null;
requestNewInterstitial(maxRetry-1);
}
//delay of 10 seconds
}, 10000);
}
});
}
}
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd != null) {
mInterstitialAd.show(Activityone.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
}
});

Do I need to check if the device is connected to the internet to request new interstitial?

I have integrated Admob ads in my app and the I working fine, but I don´t know if I can omit the step of checking if the device is connected to the internet to request an interstitial ad.
This is my code:
//connectiondetec.java:
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
//noinspection deprecation
NetworkInfo[] info = connectivity.getAllNetworkInfo();
for (NetworkInfo anInfo : info)
if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
//Activityone.java:
#Override
protected void onResume() {
super.onResume();
CallNewInertial();
}
private void CallNewInertial() {
ConnectionDetector cd = new ConnectionDetector(Activityone.this);
if (cd.isConnectingToInternet()) {
requestNewInterstitial();
}
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
mInterstitialAd = null;
requestNewInterstitial();
}
});
}
So, could I delete the connection detector class so that now the CallNewInertial is changed to the following code?
private void CallNewInertial() {
requestNewInterstitial();
}
updated code to make it work perfect:
#Override
protected void onResume() {
super.onResume();
requestNewInterstitial(5);
}
private void requestNewInterstitial(int maxRetry) {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
if (maxRetry>0){
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
mInterstitialAd = null;
requestNewInterstitial(maxRetry-1);
}
}, 10000);
}
});
}
}
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd != null) {
mInterstitialAd.show(Activityone.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
}
});
It's not a common practice to check the internet connection before loading ad. It's also not very common to reload ad when it failed to load, because usually you start loading a new Interstitial anyway when entering next screen / loading next game level.
However, if your app does not have "natural" points when you request a new ad, then it's fine to reload it in onAdFailedToLoad, but limit the attempts to let's say 3 times and optionally add some delay before next attempt.

Google Admob Ad crashes app while loading interstitial ad

my app crashes while loading Google Admob ad. It worked fine for a long time but now I get following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.interstitial.InterstitialAd.setFullScreenContentCallback(com.google.android.gms.ads.FullScreenContentCallback)' on a null object reference
I've changed nothing in code, my app is in Play Store and I have the App on my Galaxy S10 & it worked all the time but now if the Ad has to be loaded I get this error. Can somebody help?
Thanks
Edit: Here's my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-93706071examplenumber/4141725063", adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
Log.i("TAG", "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
Log.i("TAG", "onAdLoaded");
mInterstitialAd = null;
}
});
private void showInterstitial(){
if (callbackActive == false){
setCallback();
}
if (mInterstitialAd != null ) {
mInterstitialAd.show(MainActivity.this);
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
}
private void setCallback(){
callbackActive = true;
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdDismissedFullScreenContent() {
Log.d("TAG", "The ad was dismissed.");
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
Log.d("TAG", "The ad failed to show.");
}
#Override
public void onAdShowedFullScreenContent() {
mInterstitialAd = null;
Log.d("TAG", "The ad was shown.");
}
});
}
Put setFullScreenContentCallback in onAdLoaded
here is a code snippet (see code below) and check the full code from AdMob official sample on GitHub
public void loadAd() {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(
this,
AD_UNIT_ID,
adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
MyActivity.this.interstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
Toast.makeText(MyActivity.this, "onAdLoaded()", Toast.LENGTH_SHORT).show();
interstitialAd.setFullScreenContentCallback(
new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
// Make sure to set your reference to null so you don't
// show it a second time.
MyActivity.this.interstitialAd = null;
Log.d("TAG", "The ad was dismissed.");
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
// Make sure to set your reference to null so you don't
// show it a second time.
MyActivity.this.interstitialAd = null;
Log.d("TAG", "The ad failed to show.");
}
#Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
Log.d("TAG", "The ad was shown.");
}
});
}

Pass username to another activity with RewardedAd

The problem is that I am trying to pass the name of the user when the adReward is complete to another activity. But I'm stuck in this activity, even though the video ad is loaded. (and it works well while there are no video ad to show). Here is my code:
My java.class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
Vibrator vibrator;
private RewardedVideoAd HDay1;
int currentActivity = 0;
boolean flag;
private EditText vname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_day1);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
MobileAds.initialize(this,
"ca-app-pub-3940256099942544/6300978111");
///ADD BAN
AdView mAdView = findViewById(R.id.banner1);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
///////////////////////////////////
//VIDEO
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
loadRewardedVideoDAY1();
vname = findViewById(R.id.name);
final ImageView nm = findViewById(R.id.ID);
nm.setVisibility(View.INVISIBLE);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
nm.setColorFilter(filter);
final Button closeAd = findViewById(R.id.closeDay1);
closeAd.setVisibility(View.INVISIBLE);
///////////////////////////////////////////////////////////////////////////////////////////
closeAd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vibrator.vibrate(50);
loadRewardedVideoDAY1();
if (HDay1.isLoaded()) {
HDay1.show();
setCurrent(1);
}
String name = vname.getText().toString();
getusername(name);
}
});
}
////////////////////////////////////////////////////////////////
private void Day1() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void getusername(String name) {
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void loadRewardedVideoDAY1() {
if (!HDay1.isLoaded()) {
HDay1 = null;
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
///////////////TEST ID//////////////////
HDay1.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d("LOADED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdOpened() {
Log.d("OPENED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoStarted() {
Log.d("STARTED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoDAY1();
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewarded(RewardItem rewardItem) {
loadRewardedVideoDAY1();
flag = true;
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
#Override
protected void onPause() {
HDay1.pause(this);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void setCurrent(int val){
currentActivity = val;
}
Any idea what the problem could be? Thanks in advance
Try below code. Update ProcessData with your intent logic and update oncreate with other data required in your class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
private Boolean bRewardVideo = false;
#Override
public void onResume() {
super.onResume();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.resume(this);
}
}
#Override
public void onPause() {
super.onPause();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.pause(this);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.destroy(this);
}
}
#Override
public void onRewardedVideoCompleted() {
//Toast.makeText(this, "onRewardedVideoCompleted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLoaded() {
//Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
//Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoStarted() {
//Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
//Toast.makeText(this, "Reward Video Closed", Toast.LENGTH_SHORT).show();
// Load the next rewarded video ad.
if (bRewardVideo) {
ProcessData();
} else {
Toast.makeText(this, "Please View Reward Video to get Reward Points", Toast.LENGTH_LONG).show();
}
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, "Now you can close Ad to Process", Toast.LENGTH_LONG).show();
bRewardVideo = true;
}
#Override
public void onRewardedVideoAdLeftApplication() {
//Toast.makeText(this, "onRewardedVideoAdLeftApplication",Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Toast.makeText(this, "Fail to Load Reward Video. Please try again!", Toast.LENGTH_SHORT).show();
}
private void loadRewardedVideoAd() {
bRewardVideo = false;
mRewardedVideoAd.loadAd(BuildConfig.REWARDVIDEOID,
new AdRequest.Builder().build());
}
private void ProcessData() {
Snackbar.make(findViewById(R.id.drawer_layout_law), "Please wait while we process the request... ", Snackbar.LENGTH_INDEFINITE).show();
//WRITE YOUR INTENT CODE HERE
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void ShowRewardVideoDialog() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
} else {
loadRewardedVideoAd();
Toast.makeText(mctx, "Fail to Load Reward Video : Please try again", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
}

Categories

Resources