Process the value of preference before save in And

2019-02-03 15:06发布

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条回答
疯言疯语
2楼-- · 2019-02-03 16:04

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.

查看更多
登录 后发表回答