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

  • Thread starter Thread starter Darkmisc
  • Start date Start date
AI Thread Summary
The discussion revolves around issues encountered while implementing rewarded interstitial ads in an Android application using AdMob. The primary problem is a Null Pointer Exception occurring when attempting to show the ad, specifically due to the `rewardedInterstitialAd` being null. This happens because the ad may not have been loaded successfully before the button is clicked. A suggested solution is to change the method call from `rewardedInterstitialAd.show(MainActivity.this, MainActivity.this);` to `rewardedInterstitialAd.show(this, this);`, as the latter is more appropriate within the context of the class.Further complications arise when users attempt to show multiple ads in succession, leading to crashes. This is attributed to the need for reloading the ad after it has been displayed. It is recommended to implement a method that handles ad loading and ensure that the ad is ready before allowing another display attempt. The conversation highlights the importance of managing ad load states effectively to prevent crashes and ensure a smooth user experience.
Darkmisc
Messages
222
Reaction score
31
TL;DR Summary
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 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.
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.
Thread 'Project Documentation'
Trying to package up a small bank account manager project that I have been tempering on for a while. One that is certainly worth something to me. Although I have created methods to whip up quick documents with all fields and properties. I would like something better to reference in order to express the mechanical functions. It is unclear to me about any standardized format for code documentation that exists. I have tried object orientated diagrams with shapes to try and express the...

Similar threads

Back
Top