如何在 android 中使用 getSharedPreferences

我有一个应用程序,我必须在其中实现一个“登录”活动:

  1. 用户名
  2. 编辑文本密码
  3. 按钮登录
  4. 取消按钮

我希望我的应用程序能够在用户登录后记住用户的登录细节,直到用户按下“注销”按钮。我没有在 xml 中使用首选项。

如何让 getSharedPreferences (String name,int mode)在应用程序中工作?

172155 次浏览

First get the instance of SharedPreferences using

SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);

Now to save the values in the SharedPreferences

Editor edit = userDetails.edit();
edit.putString("username", username.getText().toString().trim());
edit.putString("password", password.getText().toString().trim());
edit.apply();

Above lines will write username and password to preference

Now to to retrieve saved values from preference, you can follow below lines of code

String userName = userDetails.getString("username", "");
String password = userDetails.getString("password", "");

(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)

//Set Preference
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor prefsEditor;
prefsEditor = myPrefs.edit();
//strVersionName->Any value to be stored
prefsEditor.putString("STOREDVALUE", strVersionName);
prefsEditor.commit();


//Get Preferenece
SharedPreferences myPrefs;
myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
String StoredValue=myPrefs.getString("STOREDVALUE", "");

Try this..

After reading around alot, only this worked: In class to set Shared preferences:

SharedPreferences userDetails = getApplicationContext().getSharedPreferences("test", MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.clear();
edit.putString("test1", "1");
edit.putString("test2", "2");
edit.commit();

In AlarmReciever:

SharedPreferences userDetails = context.getSharedPreferences("test", Context.MODE_PRIVATE);
String test1 = userDetails.getString("test1", "");
String test2 = userDetails.getString("test2", "");

If someone used this:

val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)

PreferenceManager is now depricated, refactor to this:

val sharedPreferences = context.getSharedPreferences(context.packageName + "_preferences", Context.MODE_PRIVATE)