Why do I get a Null Pointer Exception when I try to run rewarded ads?

  • Thread starter Thread starter Darkmisc
  • Start date Start date
Click For Summary

Discussion Overview

The discussion revolves around a Null Pointer Exception encountered when attempting to run rewarded interstitial ads in an Android application. Participants are examining the code implementation and potential causes of the error, focusing on the ad loading and display process.

Discussion Character

  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant reports a Null Pointer Exception occurring when calling the method to show the rewarded interstitial ad, indicating that the ad reference may not be properly initialized.
  • The same participant shares their code and stack trace, suggesting that the issue arises when the button click triggers the ad display.
  • There is a mention of the ad being loaded asynchronously, which raises questions about whether the ad is ready to be shown at the time of the button click.
  • Some participants propose checking if the ad is null before attempting to show it, as a potential solution to avoid the exception.
  • Others discuss the importance of ensuring that the ad loading process completes successfully before any attempt to display the ad is made.

Areas of Agreement / Disagreement

Participants generally agree that the Null Pointer Exception is likely due to the ad not being loaded or initialized properly. However, there is no consensus on the exact cause or the best approach to resolve the issue, as multiple potential solutions are being discussed.

Contextual Notes

Some limitations noted include the asynchronous nature of ad loading, which may affect the timing of when the ad is available for display. Additionally, the specific conditions under which the ad fails to load or show are not fully explored.

Darkmisc
Messages
222
Reaction score
31
TL;DR
I copied code from the Admob developer page for a rewarded ad and it doesn't work. I get a Null Pointer Exception.
Hi everyone

I've cut and pasted code from here to test rewarded interstitial ads. https://developers.google.com/admob/android/rewarded-interstitial
The only change I've made is to call the ad upon a button click.

When I click the button to call the ad, the program crashes and makes reference to a Null Pointer Exception caused by the following lines:
[CODE lang="java" title="line with error"]rewardedInterstitialAd.show(/* Activity */ MainActivity.this,/*
OnUserEarnedRewardListener */ MainActivity.this);
[/CODE]

Does anyone know why this is happening?

Full code and stacktrace below.
Thanks
[CODE lang="java" title="MainActivity" highlight="62-63"]import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.OnUserEarnedRewardListener;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAd;
import com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAdLoadCallback;

public class MainActivity extends AppCompatActivity implements OnUserEarnedRewardListener {
private RewardedInterstitialAd rewardedInterstitialAd;
private String TAG = "MainActivity";

TextView textView;
Button button;
int value;

@Override
public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
Log.i(TAG, "User earned reward.");
value++;
textView.setText(String.valueOf(value));
}

@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

int value =0;
textView = findViewById(R.id.textView);
textView.setText(String.valueOf(value));
button = findViewById(R.id.button); MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});

loadAd();
}

public void onClick (View view){
**rewardedInterstitialAd.show(/* Activity */ MainActivity.this,/*
OnUserEarnedRewardListener */ MainActivity.this);**
}

public void loadAd(){
RewardedInterstitialAd.load(MainActivity.this, "ca-app-pub-3940256099942544/5354046379",
new AdRequest.Builder().build(), new RewardedInterstitialAdLoadCallback() {
@Override
public void onAdLoaded(RewardedInterstitialAd ad) {
rewardedInterstitialAd = ad;
rewardedInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
@Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
Log.d(TAG, "Ad was clicked.");
}

@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.
Log.d(TAG, "Ad dismissed fullscreen content.");
rewardedInterstitialAd = null;
}

@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
Log.e(TAG, "Ad failed to show fullscreen content.");
rewardedInterstitialAd = null;
}

@Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
Log.d(TAG, "Ad recorded an impression.");
}

@Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d(TAG, "Ad showed fullscreen content.");
}
});
}
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
Log.d(TAG, loadAdError.toString());
rewardedInterstitialAd = null;
}
});
}
}
[/CODE]

Here is the stacktrace.[CODE lang="java" title="stacktrace" highlight="34-35"]E FATAL EXCEPTION: main
Process: com.xxmassdeveloper.rewardedads2, PID: 20217
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:473)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:468)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
**Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAd.show(android.app.Activity, com.google.android.gms.ads.OnUserEarnedRewardListener)' on a null object reference
at com.xxmassdeveloper.rewardedads2.MainActivity.onClick(MainActivity.java:64)**
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:468)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
2023-02-01 10:30:03.908 20217-20217 Process com.xxmassdeveloper.rewardedads2 I Sending signal. PID: 20217 SIG: 9
---------------------------- PROCESS ENDED (20217) for package com.xxmassdeveloper.rewardedads2 ----------------------------
2023-02-01 10:30:04.207 3675-5653 WindowManager pid-3675 E win=Window{81ddba7 u0 com.xxmassdeveloper.rewardedads2/com.xxmassdeveloper.rewardedads2.MainActivity EXITING} destroySurfaces: appStopped=false win.mWindowRemovalAllowed=true win.mRemoveOnExit=true win.mViewVisibility=0 caller=com.android.server.wm.AppWindowToken.destroySurfaces:1200 com.android.server.wm.AppWindowToken.destroySurfaces:1181 com.android.server.wm.WindowState.onExitAnimationDone:5030 com.android.server.wm.-$$Lambda$01bPtngJg5AqEoOWfW3rWfV7MH4.accept:2 java.util.ArrayList.forEach:1262 com.android.server.wm.AppWindowToken.onAnimationFinished:3549 com.android.server.wm.AppWindowToken.commitVisibility:860
[/CODE]
 
Last edited:
Technology news on Phys.org
Darkmisc said:
When I click the button to call the ad, the program crashes and makes reference to a Null Pointer Exception caused by the following lines:
[CODE lang="java" title="line with error"]rewardedInterstitialAd.show(/* Activity */ MainActivity.this,/*
OnUserEarnedRewardListener */ MainActivity.this);
[/CODE]

Does anyone know why this is happening?
You were supposed to pass an instance of the Activity class and OnUserEarnedRewardListener interface. Why are you passing MainActivity.this? Just pass this, you are already inside the MainActivity class, which is also an instance of the interface as you have implemented it.

The correct method call would be:
[CODE lang="java" title="Corrected code"]rewardedInterstitialAd.show(this, this);
[/CODE]

Classname.this is a different thing. See https://stackoverflow.com/q/45637427/8387076

Also, your deleted question on Stack Overflow is still popping up in search queries o0)
 
Last edited:
  • Like
  • Haha
Likes   Reactions: Darkmisc and jedishrfu
Thanks. It worked, but I can only click on the button once and see an ad. If I try to watch more than one ad in a row, the program crashes (stacktrace below).

If I wait a bit and then try, I can see the ad again, but I can't click the button again without a crash.

Does this have anything to do with load times? I don't understand why the button shouldn't work all the time.

[CODE lang="java" title="stacktrace" highlight="34-35"]FATAL EXCEPTION: main
Process: com.xxmassdeveloper.rewardedads2, PID: 6960
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:473)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:468)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAd.show(android.app.Activity, com.google.android.gms.ads.OnUserEarnedRewardListener)' on a null object reference
at com.xxmassdeveloper.rewardedads2.MainActivity.onClick(MainActivity.java:65)
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:468)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
2023-02-02 11:45:28.182 6960-6960 Process com.xxmassdeveloper.rewardedads2 I Sending signal. PID: 6960 SIG: 9
---------------------------- PROCESS ENDED (6960) for package com.xxmassdeveloper.rewardedads2 ----------------------------
2023-02-02 11:45:28.304 3675-5805 WindowManager pid-3675 E win=Window{e12d993 u0 com.xxmassdeveloper.rewardedads2/com.xxmassdeveloper.rewardedads2.

Activity EXITING} destroySurfaces: appStopped=false win.mWindowRemovalAllowed=true win.mRemoveOnExit=true win.mViewVisibility=0 caller=com.android.server.wm.AppWindowToken.destroySurfaces:1200 com.android.server.wm.AppWindowToken.destroySurfaces:1181 com.android.server.wm.WindowState.onExitAnimationDone:5030 com.android.server.wm.-$$Lambda$01bPtngJg5AqEoOWfW3rWfV7MH4.accept:2 java.util.ArrayList.forEach:1262 com.android.server.wm.AppWindowToken.onAnimationFinished:3549 com.android.server.wm.AppWindowToken.commitVisibility:860
[/CODE]
 
One error I see is that in the full code you posted in the OP, the loadAd() method call at line 58 should be inside the nested class, i.e. between lines 54 and 55.

Note that in the loadAd() method, you are inside a nested class, you have to use MainActivity.this instead of just this, which is what you've already done.

If this change doesn't solve the issue, then I think you have to initialize the ad again once it has been showed (call the nested class callback from line 52 again). Separate this portion out in a method to call easily.
 
  • Like
Likes   Reactions: Darkmisc

Similar threads

  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 6 ·
Replies
6
Views
6K