开发者

Process the value of preference before save in Android?

开发者 https://www.devze.com 2023-03-02 12:01 出处:网络
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 preferen

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.prefer开发者_JAVA技巧ences);

            // 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消