2016-02-28 139 views
1

我想顯示一個彈出窗口,如果用戶點擊不再顯示,我想不再顯示它。但是,dont show again按鈕不起作用。我使用的共享偏好:只顯示一次?

 if (dialogPrefs.getBoolean("Show", true) == true) { 

      new AlertDialog.Builder(this) 
        .setTitle("Blah") 
        .setMessage("Blah blah blah ") 
        .setNegativeButton("Not now", null) 
        .setNeutralButton("Don't show again", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int which) { 
          dialogEditor = dialogPrefs.edit(); 
          dialogEditor.putBoolean("Show", false); 
          dialogEditor.commit(); 
         } 
        }) 
        .setPositiveButton("Enable", new DialogInterface.OnClickListener() { 

         public void onClick(DialogInterface dialog, int which) { 
         enable(); 
         } 
        }).show(); 

我的喜好和編輯聲明在開頭這樣:

SharedPreferences dialogPrefs; 
SharedPreferences.Editor dialogEditor; 

共享首選項在onCreate()初始化。

請讓我知道問題可能是什麼。

謝謝,

Ruchir

+1

請顯示你如何在onCreate方法中初始化dialogPrefs和dialogEditor,或者發佈完整代碼 – appersiano

回答

0

SharedPreferences.Editor.commit()返回一個布爾值,表示寫入到實際SharedPreferences對象的狀態。看看commit()返回true。另外,請確保您沒有使用兩個編輯器編輯相同的SharedPreference。最後一位編輯提交的內容將反映出其變化。

更新當我運行它時,您的代碼正常工作。我的代碼中沒有看到任何錯誤。請確保您正在寫入並閱讀相同的SharedPreferences。

+0

它返回true –

0

您的問題是SharedPreferences的聲明;這是所有宣佈,但...沒有初始化!操作系統應該在哪裏寫入鍵值數據?

我建議你閱讀本Get a Handle to a SharedPreferences

試試這個代碼,我測試了它和工作:

SharedPreferences dialogPrefs = this.getPreferences(Context.MODE_PRIVATE); 
final SharedPreferences.Editor dialogEditor = dialogPrefs.edit(); 


if (dialogPrefs.getBoolean("Show", true)) { 

    new AlertDialog.Builder(this) 
      .setTitle("Blah") 
      .setMessage("Blah blah blah ") 
      .setNegativeButton("Not now", null) 
      .setNeutralButton("Don't show again", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        dialogEditor.putBoolean("Show", false); 
        dialogEditor.commit(); 
       } 
      }) 
      .setPositiveButton("Enable", new DialogInterface.OnClickListener() { 

       public void onClick(DialogInterface dialog, int which) { 
        Log.i("TAG", "onClick: enable"); 
       } 
      }).show(); 
} 
} 
+0

它被初始化,看看我的答案的底部,我聲明它在開始時聲明。 –

+0

ruchir是它宣佈但沒有初始化 – appersiano

+0

哦,我很抱歉,我忘了顯示初始化。它實際上是在onCreate()中初始化的。我會編輯我的問題:) –

0

它應該是這樣的:

if (!dialogPrefs.getBoolean("Show", false)) {//don't show again will work 

代替:

if (dialogPrefs.getBoolean("Show", true) == true) {//this will always show dialog