Question

I am creating AlertDialog onBackPressed with Exit and Rate App buttons. AlertDialog will show only once if person rate app, that part is working fine. But the problem is, after someone rate app, boolean changes, app will not show AlertDialog so onBackPressed will be disabled. How can I change that? Here is my code:

 @Override
    public void onBackPressed() {

        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        if (!prefs.getBoolean("firstTime", false)) {
    new AlertDialog.Builder(this)
    .setCancelable(false)
        .setTitle("Rate us")
        .setMessage("Thank you for choosing our app! We will be very thankful if you can spend your valuable time to give this app a good rate in Google Play market!")
        .setPositiveButton("Rate us", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { 
                Uri uri = Uri.parse("market://details?id=" + getPackageName());
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);

    SharedPreferences.Editor editor = prefs.edit();
          editor.putBoolean("firstTime", true);
          editor.commit();
            }
         })
        .setNegativeButton("Exit", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { 
                ((Activity) context).finish();
            }
         })

         .show();


        };

    }


  }

I added

if (!prefs.getBoolean("firstTime", true)){
            ((Activity) context).finish();
}

But it didn't do anything. onBackPressed was still disabled. to summarize: After Changing Boolean firstTime, onBackPressed is disabled and I can't leave/close app using that button. How can I fix that?

Was it helpful?

Solution

Simple just add else part to handle this like:

@Override
    public void onBackPressed() {
        super.onBackPressed();


        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        if (!prefs.getBoolean("firstTime", false)) {
            //show your dialog
        }else{
            super.onBackPressed();
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top