title: Preference Activity
body: <p>I am creating a settings activity for my android application, one of the options it to allow password or not, I do not just want that option to be checked anyhow so I want it to ask for a password before changing the preference. I want a Dialog fragment to pop up and ask for the password before the preference changes, after changing, the <strong>onPreferenceChange</strong> method should be called and if the password is correct the preference can change by returning <strong>true</strong>;</p>
  
  <p>The issue is that my settings fragment cannot recognize <strong>getFragmentManager()</strong>  and even if I do <strong>getActivity.getFragmentManager</strong> it gives an error that the <strong><em>preferencefragment cannot be cast to the dialog</em></strong>. The dialog works for normal activities in the project but not the preference fragment.</p>
  
  <p>This is the dialogfragment showing where the activity is to be casted</p>
  
  <pre><code>public class password_dialog extends DialogFragment {
  public interface PasswordDialogListener {
      void onDialogPositiveClick(DialogFragment dialog, String password);
  
      void onDialogNegativeClick(DialogFragment dialog);
  }
  
  PasswordDialogListener mListener;
  
  
  @Override
  public void onAttach(Context activity) {
      super.onAttach(activity);
      // Verify that the host activity implements the callback interface
      try {
          // Instantiate the PasswordDialogListener so we can send events to the host
          mListener = (PasswordDialogListener) activity;
      } catch (Exception e) {
        Log.e("dialog",e.getMessage());
      }
  }
  </code></pre>
  
  <p>.
  .
  .</p>
  
  <p>This is the main code of the preference fragment the class extends extends <strong>PreferenceFragmentCompat</strong> and <strong>implements Preference.OnPreferenceChangeListener, password_dialog.PasswordDialogListener</strong></p>
  
  <pre><code> @Override
  public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
      addPreferencesFromResource(R.xml.preferences);
      Preference preference = findPreference(getString(R.string.printSetting));
  
      /*****Realm*****/
      Realm.init(getActivity());
      realm = Realm.getDefaultInstance();
  
      preference.setOnPreferenceChangeListener(this);
  }
  
  @Override
  public boolean onPreferenceChange(Preference preference, Object newValue) {
      DialogFragment PasswordDialogFragment = new password_dialog();
      PasswordDialogFragment.show(getFragmentManager(), "Password");
  
      if (passwordIsCorrect) {
          return true;
      } else {
          return false;
      }
  
  }
  </code></pre>
  
  <p>And because of that it gives a null pointer exception because <strong>mListener</strong> is not initialized.</p>