简体   繁体   中英

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.

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

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

infoEditor.commit()似乎后失踪infoEditor.putBoolean("firstLaunch", false) ,因此新的值永远不会被保存。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM