androidandroid-studioadsinterstitial

Android: My App keep crashing when offline


I just implemented banner-Interstitial ads in my app today, my app is a game it's supposly online game but i noticed that if user is offline the game would open and i have no problem with this, but the problem is that whenever any activity or place that have an Interstitial ads the app would crash if no internet connection so how to solve this problem ?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_anagram);

    questionCounter = findViewById(R.id.questionCounter);


    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

    tv_info = findViewById(R.id.tv_info);
    tv_word = findViewById(R.id.tv_word);
    et_guess = findViewById(R.id.et_guess);
    b_check = findViewById(R.id.b_check);
    guessItTimer = findViewById(R.id.guessItTimer);
    scaling = AnimationUtils.loadAnimation(this,R.anim.scale);


    //ads
    MobileAds.initialize(this, new OnInitializationCompleteListener() {
        @Override
        public void onInitializationComplete(@NonNull InitializationStatus initializationStatus) {

        }
    });

    AdRequest adRequest1 = new AdRequest.Builder().build();
    // Attempt loading ad for interstitial
    InterstitialAd.load(this,"MyAd--ID", adRequest1,
            new InterstitialAdLoadCallback() {
                @Override
                public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                    // The mInterstitialAd reference will be null until
                    // an ad is loaded.
                    mInterstitialAd = interstitialAd;
                    Log.i("TAG", "onAdLoaded");
                }

                @Override
                public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                    // Handle the error
                    Log.i("TAG", loadAdError.getMessage());
                    mInterstitialAd = null;
                }
            });

    r = new Random();

    newGame();
    checkAnswer();

}

private String shuffleWord(String word){
    List<String> letters = Arrays.asList(word.split(""));
    Collections.shuffle(letters);
    String shuffled = "";
    for(String letter: letters){
        shuffled += letter;
    }
    return shuffled;
}

private void newGame(){
    //get random word from dictionary
    currentWord = dictionary[r.nextInt(dictionary.length)];

    // show the shuffled word
    tv_word.setText(shuffleWord(currentWord));
    et_guess.setText("");
    b_check.setEnabled(true);
    //so tv_info color change and not to cancel the other request
    if (tv_info.getText().toString() == "Fantastic!"){
        tv_info.setVisibility(View.VISIBLE);
    } else{
        tv_info.setVisibility(View.INVISIBLE);
    }
}

//CountdownTimer
public void resetTimer() {
    timer = new CountDownTimer(35150, 1000) {
        @Override
        public void onTick(long l) {
            int timerColor = Integer.parseInt(guessItTimer.getText().toString());
            guessItTimer.setText(String.valueOf(l / 1000));
            //Animation for timer and color
            if (timerColor < 11 && timerColor >= 1) {
                guessItTimer.setTextColor(Color.parseColor("#E10F0F"));
                guessItTimer.startAnimation(scaling);//----------------->
            }

        }

        @Override
        public void onFinish() {
            Toast.makeText(AnagramActivity.this, "Time is over", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(AnagramActivity.this, anagramAgainActivity.class));
            finish();
        }
    }.start();
}

public void onBackPressed() {
    super.onBackPressed();
    timer.cancel();
    mInterstitialAd.show(AnagramActivity.this);
    this.finish();
}

public void checkAnswer() {
    b_check.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(et_guess.getText().toString().equalsIgnoreCase(currentWord)){
                tv_info.setVisibility(View.VISIBLE);
                tv_info.setTextColor(Color.GREEN);
                tv_info.setText("Fantastic!");
                b_check.setEnabled(false);

                // set count of numb of question answered
                index = index +1;
                String ar = String.valueOf(index);
                questionCounter.setText(ar);

                newGame();

            } else {
                tv_info.setVisibility(View.VISIBLE);
                tv_info.setTextColor(Color.RED);
                tv_info.setText("Try Again!");
            }
        }
    });
    resetTimer();
}

}


Solution

  • You are calling mInterstitialAd.show(AnagramActivity.this); in onBackPressed() method. When the App is offline, mInterstitialAd is null, which is causing the crash. Add a condition to show Ad only when it loaded (mInterstitialAd is not null).

    public void onBackPressed() {
        super.onBackPressed();
        timer.cancel();
        if(mInterstitialAd !=null)
        mInterstitialAd.show(AnagramActivity.this);
        this.finish();
    }