java - 安卓错误: Unable to resume activity Adview on a null object reference

标签 java android admob

我正在尝试修复游戏中的计费问题。现在一切都很好,除非我购买了一个元素(也应该删除广告)并且我重新加载游戏,游戏在加载屏幕时崩溃。 我发现 Main.java onResume Activity 有问题,并且需要与 Adview 相关,但我不熟悉它。

Here is the logcat error:
    E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to resume activity {com.games.finddifference2.hd/com.games.finddifference2.hd.Main}:
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.a()' on a null object reference
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3333)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3364)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2671)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1493)
    at android.os.Handler.dispatchMessage(Handler.java:111)
    at android.os.Looper.loop(Looper.java:207)
    at android.app.ActivityThread.main(ActivityThread.java:5769)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.a()' on a null object reference
    at com.games.finddifference2.hd.Main.onResume(SourceFile:264)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
    at android.app.Activity.performResume(Activity.java:6691)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3318)   

还有 Main.java:

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager; 
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.widget.RelativeLayout;

import com.tapjoy.TapjoyConnect; 


/**
 * The initial Android Activity, setting and initiating
 */
@SuppressLint("NewApi")
public class Main extends Activity {

    /** Our own OpenGL View overridden */
    private OpenGLRenderer openGLRenderer;
    //private final boolean isGoogle = false;
    public AdView adView;
    private InterstitialAd interstitial;

    private RelativeLayout rl;
    private RelativeLayout.LayoutParams relativeParamsTOP;
    private RelativeLayout.LayoutParams relativeParamsBOTTOM; 

    private Context mContext;
    private boolean fullgame = true;
    private boolean adshown = false;
    private boolean tapjoy = false;
    private AdRequest adRequest;


    public Handler handler = new Handler() {
        public void handleMessage(Message msg) {

            Log.i("Handler", "Handler called with code: " + msg);

            AlphaAnimation animation = new AlphaAnimation( 0.0f, 1.0f );
            animation.setDuration( 400 );
            animation.setFillAfter( true );
            animation.setInterpolator( new AccelerateInterpolator() );
            AlphaAnimation animation2 = new AlphaAnimation( 1.0f, 0.0f );
            animation2.setDuration( 400 );
            animation2.setFillAfter( true );
            animation2.setInterpolator( new AccelerateInterpolator() );

            switch(msg.what)
            {
            case 0:
                try {  
                    adView.startAnimation( animation2 );
                    adView.setVisibility(View.GONE);
                    adshown = false;
                    this.postDelayed(new Runnable() { public void run() { 
                        try {
                            //adshown = false;
                            rl.removeView(adView); 
                        } catch (Exception e) { e.printStackTrace(); }
                    } }, 400);
                } catch (Exception e) { e.printStackTrace(); }
                break;
            case 1:
                if (!fullgame && !adshown) {
                    try {  
                        adshown = true;
                        rl.addView(adView, relativeParamsBOTTOM);
                        adView.startAnimation( animation );
                        adView.setVisibility(View.VISIBLE);
                    } catch (Exception e) { e.printStackTrace(); }
                }
                break;           
            case 2:
                if (!fullgame && !adshown) {
                    try {  
                        adshown = true;
                        rl.addView(adView, relativeParamsTOP);
                        adView.startAnimation( animation );
                        adView.setVisibility(View.VISIBLE);
                    } catch (Exception e) { e.printStackTrace(); }
                }
                break;
            case 3: 
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                break;
            case 4: 
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                break;

            case 5: 
                if (interstitial.isLoaded()) {
                      interstitial.show();
                }

                    break;

                default:
                    break;
              } 
        }
    };

    /**
     * Initiate the OpenGL View and set our own
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);  

        rl = new RelativeLayout(this);
        relativeParamsTOP = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        relativeParamsBOTTOM = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 

        relativeParamsTOP.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        relativeParamsBOTTOM.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

        this.setVolumeControlStream(AudioManager.STREAM_MUSIC); 
        SoundManager.getInstance();
        SoundManager.initSounds(this);
        SoundManager.loadSounds();

        SharedPreferences pref = mContext.getSharedPreferences("Settings", Context.MODE_PRIVATE);
        fullgame = pref.getBoolean("Ads", false);

        // Create the adView
        if (!fullgame) {
            adView = new AdView(this);
            adView.setAdUnitId(getString(R.string.admob_banner_id));
                adView.setAdSize(AdSize.SMART_BANNER);  

                // Create the interstitial.
                interstitial = new InterstitialAd(this);
                interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
        }   
        // TAPJOY
        try { 
            TapjoyConnect.requestTapjoyConnect(this, "3a62180b-8dd2-487c-9af3-30e6455f562b", "X0J1DTeFNZ95yMAdcx8w");
            Log.i("Tapjoy", "Tapjoy connected");
            tapjoy = true;
        } catch (Exception e) 
        {
            e.printStackTrace();
        } 

        try {
            openGLRenderer = new OpenGLRenderer(this, handler);
        } catch (Exception e) 
        {
            e.printStackTrace();
        }

        // Add the adView to it
        rl.addView(openGLRenderer);

        if (!fullgame) {
            try {
            adView.setVisibility(View.GONE);
            adView.loadAd(new AdRequest.Builder().build()); 
            adRequest = new AdRequest.Builder().build();
            interstitial.loadAd(adRequest);   
            Log.i("Ads", "----- request loaded");
            } 
            catch (Exception e) 
             {
              e.printStackTrace();
             }
        } 
        setContentView(rl); 
    }

    /**
     * Remember to resume the glSurface
     */
    @Override
    protected void onResume() {
        super.onResume();
        openGLRenderer.onResume();
        adView.resume(); 

        Log.i("OpenGL", "onResume called");

            if (interstitial != null && adRequest != null) {
            interstitial.loadAd(adRequest);
            } else {
            interstitial = new InterstitialAd(this);
            interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
            adRequest = new AdRequest.Builder().build();
            interstitial.loadAd(adRequest);
            }

    }

    /**
     * Also pause the glSurface
     */
     @Override
      public void onStart() {
        super.onStart();
        final SharedPreferences settings =
            getSharedPreferences("localPreferences", MODE_PRIVATE);
        if (settings.getBoolean("isFirstRun", true)) {

            new AlertDialog.Builder(this)
                .setMessage("We use device identifiers and share it with our partners to improve your user experience. See details in Privacy Policy.")
                .setNeutralButton ("Privacy Policy", new DialogInterface.OnClickListener () {
                    @Override
                    public void onClick (DialogInterface dialog, int which) {
                        openBrowserLink (Main.this, "http://test.com");
                    }
                })
                .setPositiveButton ("Ok", new DialogInterface.OnClickListener () {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        settings.edit().putBoolean("isFirstRun", false).commit();
                    }
                }).show();
        }
      }

      public static void openBrowserLink (Context c, String str) {
        Intent i = new Intent (Intent.ACTION_VIEW);
        i.setData (Uri.parse (str));
        c.startActivity (i);
    }

    @Override
    protected void onPause() {
        adView.pause(); 

        openGLRenderer.onPause();
        Log.i("OpenGL", "onPause called");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        try { adView.destroy(); } catch (Exception e) { e.printStackTrace(); }
        try { openGLRenderer.onDestroy(); } catch (Exception e) { e.printStackTrace(); }
        try { SoundManager.cleanup(); } catch (Exception e) { e.printStackTrace(); }
        if (tapjoy) try { TapjoyConnect.getTapjoyConnectInstance().sendShutDownEvent(); } catch (Exception e) { e.printStackTrace(); } 
        super.onDestroy();
    }


 @Override
      public void onActivityResult(int requestCode, int resultCode, Intent data) {

            if (!openGLRenderer.mHelper.handleActivityResult(requestCode, resultCode, data)) {

                   super.onActivityResult(requestCode, resultCode, data);
           }

      } 

}

最佳答案

我不确定,但我认为是在 adView 未定义时。 在OnCreate中,如果fullgame = true -> adView未定义 -> 在 onResume 中:adView.resume() 且 adView 为 null

关于java - 安卓错误: Unable to resume activity Adview on a null object reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39342618/

相关文章:

java - 为什么 if(Boolean.TRUE) {...} 和 if(true) {...} 在 Java 中的工作方式不同

android - 在两个 Activity android 之间传递可序列化的自定义对象时出错

android - Room + RxJava2 无限循环案例

java - GWT RequestFactory,编辑 - 使用树状结构

java - 我试图在浏览器中加载我的 servlet,它给了我这个错误

java - 在 Callable 中处理 Thread.interrupted() 的正确方法?

android - 在设备上存储应用内项目数据

将 AdMob 插件添加到 Ionic 项目时出现 Xcode 错误

admob - 使用 AdMob AppOpenAds 时如何解决此错误?错误 : Code: 1

ios - 如何在 AVPlayer 中显示 AdMob 横幅?