如何存储值并从共享首选项中检索它们

时间:2016-10-09 22:19:47

标签: java android sharedpreferences

在activity1(emailpreferences)中,我通过edittext接收电子邮件。我想在重新打开应用程序时再次使用此电子邮件

这是我的代码:

public  static final String MyPREFERENCES = "MyPref";
public static final String Email = "emailkey";
SharedPreferences sharedPreferences;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.emailpreferences);

    edit1=(EditText)findViewById(R.id.editText);
    buttonpref=(Button)findViewById(R.id.button);

    sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

    buttonpref.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String email = edit1.getText().toString();

            SharedPreferences.Editor editor = sharedPreferences.edit();

            editor.putString(Email, email);

但是,完成以下操作后,将无法检索电子邮件:

public class MainActivity extends AppCompatActivity {

Text name;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
    String name = sharedPreferences.getString(Email, "email");
    Toast.makeText(this,name, Toast.LENGTH_LONG).show();
}
}

2 个答案:

答案 0 :(得分:1)

首先,您需要在编辑器上使用commit或apply命令将键指定给值。

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Email, email);
editor.commit(); //or editor.apply();

PreferenceManagerSharedPreference不同。请继续阅读。您可以通过这种方式检索值。

SharedPreferences sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String name = sharedPreferences.getString(Email, "email");

答案 1 :(得分:0)

要存储使用此:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Email, email);
editor.apply();

要检索使用此:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String savedEmail  = preferences.getString(Email, "email");

我建议你创建一个实用程序类,并创建一个存储和检索sharedPreferences的功能,这样你就不需要一次又一次地编写这个样板代码。