使用SharedPreferences的简单示例

时间:2014-07-22 11:15:12

标签: android sharedpreferences

我希望将电子邮件和密码保存在SharedPreferences上,以便他们可以在应用程序关闭后恢复。我不明白错误在哪里,应用程序关闭后的数据没有在EditText上设置。

MainActivity.java

    public class MainActivity extends Activity {
    Session session;
    EditText email, password;
    Button save;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            email=(EditText) this.findViewById(R.id.editText1);
            password=(EditText) this.findViewById(R.id.editText2);
            save=(Button) this.findViewById(R.id.button1);
            session = new Session();
            if(session.getEmail()!=null){
                email.setText(session.getEmail());
                password.setText(session.getPassword());
            }
            save.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    session.saveData(getApplicationContext(), 
                            email.getText().toString(), password.getText().toString());
                }
            });
        }
    }

Session.java

public class Session {
    SharedPreferences prefs;
    Editor editor;
    Context context;
    public static String FIRST_TIME="true";
    public static String NAME_PREFS="MY_PREFS";
    public static String EMAIL="";
    public static String PASSWORD="";

    public void saveData(Context context, String email, String password){
        this.context=context;
        prefs= context.getSharedPreferences(NAME_PREFS, Context.MODE_PRIVATE);
        editor=prefs.edit();
        editor.putString(FIRST_TIME, "false");
        editor.commit();
        editor.putString(EMAIL, email);
        editor.putString(PASSWORD,password);
        editor.commit();
    }
    public String getEmail(){
        return prefs.getString(EMAIL, null);
    }
    public String getPassword(){
        return prefs.getString(PASSWORD, null);
    }
}

1 个答案:

答案 0 :(得分:2)

EMAILPASSWORD应该是你的密钥,所以传递一些字符串作为标识符 - 存储你的价值的关键。改变它:

  public static String EMAIL="saved_email";
    public static String PASSWORD="saved_password";  

此外,当您从prefs中检索值时,需要初始化相同的内容,例如。传递getEmail()函数中的上下文:

public String getEmail(Context context){
SharedPreferences prefs = context.getSharedPreferences(NAME_PREFS, Context.MODE_PRIVATE);
return prefs.getString(EMAIL, null);
}