簡體   English   中英

我無法使用SharedPreferences

[英]I can't get SharedPreferences to work

我正在為Android開發一個應用程序,在“啟動”屏幕上,我希望它在第一次啟動該應用程序時顯示AlertDialog。 這是我的代碼:

    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();
        }

問題是,它每次都會顯示對話框。 即使我已經啟動它。 謝謝您的時間和幫助,zeokila。

我相信,你必須運行infoEditor.commit()putBoolean 在您保存新的首選項之前,它實際上並沒有保存。

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

您必須告訴編輯器進行保存。 添加infoEditor.commit(); (同步)或infoEditor.apply(); (異步)以保持您的價值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM