在Android中保存之前处理首选项的值? [英] Process the value of preference before save in Android?

查看:25
本文介绍了在Android中保存之前处理首选项的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要先加密我的密码,然后才能将其保存到本地 android 数据库.没有加密一切正常,我有preferences.xml等等.如何更改偏好值(例如密码)后调用函数?这是我的代码:

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:像这样,当我更改密码时,它会存储密码而不加密.

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

推荐答案

我通过扩展基本的 EditTextPreference 并在那里加密/解密密码来做到这一点:

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.

这篇关于在Android中保存之前处理首选项的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆