Alexandre Hitchcox
Alexandre Hitchcox

Reputation: 2753

I can't get SharedPreferences to work

I'm making an application for Android, on the Splash screen I would like it to show an AlertDialog the first time the application is launched. This is my code:

    SharedPreferences savedInfo = getSharedPreferences("SavedInfo", MODE_PRIVATE);
    SharedPreferences.Editor infoEditor = savedInfo.edit();

        boolean firstLaunch = savedInfo.getBoolean("firstLaunch", true);

        final AlertDialog importDialog = new AlertDialog.Builder(SplashActivity.this).create();

        if (firstLaunch == true) {
            importDialog.setTitle(R.string.splash_import_title);
            importDialog.setMessage(getString(R.string.splash_import_text));
            importDialog.setIcon(android.R.drawable.ic_dialog_alert);
            importDialog.setButton(getString(R.string.splash_import_yes), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    //ALL FILE STUFF HERE
                    importDialog.dismiss();
                    startTimer();
                }
            });
            importDialog.setButton2(getString(R.string.splash_import_no), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    importDialog.dismiss();
                        startTimer();
                }
            });  
            importDialog.show();
            infoEditor.putBoolean("firstLaunch", false);
        } else {
            startTimer();
        }

The problem is, it shows me the dialog everytime. Even when I have already launched it. Thanks for your time and help, zeokila.

Upvotes: 0

Views: 262

Answers (3)

Miker010
Miker010

Reputation: 31

infoEditor.commit() seems to be missing after infoEditor.putBoolean("firstLaunch", false), so the new value is never been saved.

Upvotes: 1

JRaymond
JRaymond

Reputation: 11782

You have to tell your editor to save. add infoEditor.commit(); (synchronous) OR infoEditor.apply(); (async) to persist your value.

Upvotes: 1

Tim
Tim

Reputation: 35943

I believe you have to run infoEditor.commit() after putBoolean. It doesn't actually save the new preference until you do so.

http://developer.android.com/reference/android/content/SharedPreferences.Editor.html

Upvotes: 1

Related Questions