One-time AlertDialog showing on every run

I am trying to have a disclaimer pop up when the app is first run, and after each update. I did a bunch of googling and reviewed some questions here as well, and this is what my code looks like:

SharedPreferences pref = getSharedPreferences("Preferences", MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
String lver = pref.getString("Version", "");
String ver = this.getString(R.string.version);
if(ver != lver)
{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Disclaimer")
        .setMessage(this.getString(R.string.disclaimer))
        .setCancelable(false)
        .setPositiveButton("Accept", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                accepted = true;
                dialog.cancel();
            }
        })
        .setNegativeButton("Decline", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                MainMenu.this.finish();
            }
        });
    AlertDialog disc = builder.create();
    disc.show();
    if(accepted == true)
    {
        edit.putString("Version", this.getString(R.string.version));
        edit.commit();
    }
}

This code actually worked at first, but when I changed my apps starting activity, and moved this code from the original starting activity to the new one, it no longer works. The disclaimer appears on every run.

I want the popup only to show on first run and after updates. What do I need to do to achieve this? I am very frustrated and confused by the fact that it was working, then wasnt.

Upvotes: 0

Views: 1848

Answers (1)

aamit915
aamit915

Reputation: 519

Comparing Strings with .equals() is the correct way (see: How do I compare strings in Java? for a good explanation) , although because I'm not sure how the android internals work and you said it worked before, that isn't your problem. Your problem is that your check

if (accepted == true) {/** code */}

isn't run on the on click listener. Because it isn't, that thread (I'm assuming it spawns a new thread to show the dialog) keeps running.

I'm also assuming before you moved this code, you had declared a

boolean accepted = true; //or initialized it to true somewhere

But when you moved it you didn't reinitialize it. Now, because the default value of a primitive is false, in your new code it gets to the check before you press a dialog button, and never commit the new version.

My advice would be put what's in the

accepted == true

block simply into your listener for the positive button click.

Upvotes: 3

Related Questions