Process the value of preference before save in Android?

最后都变了- 提交于 2019-11-29 03:20:22

问题


I need to crypt my password before save it to local android database. Everything work fine without encryption, I have preferences.xml and so. How can I call a function after I change value of preference (for example, password) ? Here is my code:

public class Preferences extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);

            // Get the custom preference
            Preference customPref = (Preference) findPreference("pass");

            customPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                String crypto = SimpleCrypto.encrypt("MYSECRETKEY", newValue.toString()); // encrypt
                // Here is where I'm wrong, I guess.
                SharedPreferences settings = getSharedPreferences("preferences", MODE_PRIVATE);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("pass", crypto);
                editor.commit();
            });
    }
}

P.S: Like this, when I change password, it stores password without encryption.


回答1:


I did this by extending the base EditTextPreference and encrypting/decrypting the password there:

public class EncryptedEditTextPreference extends EditTextPreference {
  public EncryptedEditTextPreference(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  public EncryptedEditTextPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public EncryptedEditTextPreference(Context context) {
    super(context);
  }

  @Override
  public String getText() {
    String value = super.getText();
    return SecurityUtils.decrypt(value);
  }

  @Override
  protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
    super.setText(restoreValue ? getPersistedString(null) : (String) defaultValue);
  }

  @Override
  public void setText(String text) {
    if (Utils.isStringBlank(text)) {
      super.setText(null);
      return;
    }
    super.setText(SecurityUtils.encrypt(text));
  }
}

There are some calls to my personal utilities, but I think the code is pretty clear in what you need to do.



来源:https://stackoverflow.com/questions/5858790/process-the-value-of-preference-before-save-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!