我正在开发一个应用程序,其中我正在使用SharedPreferences
存储username
和password
。一切都很好,我可以成功地存储和检索值。但是当我重新启动设备或强制关闭应用程序时,存储在SharedPreferences
中的值将被重置。当我再次启动我的应用程序时,SharedPreferences
键中的值变为null。这里是我存储值的代码:
SharedPreferences emailLoginSP;
emailLoginSP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
emailLoginSP.edit().putString("prefEmailId", email_text).commit();
emailLoginSP.edit().putString("prefUserId", userIDToken).commit();
emailLoginSP.edit().putString("prefAccess_token", accessToken).commit();
Intent i = new Intent(LoginWithEmail.this,UserInfoActivity.class);
i.putExtra("acess_token", accessToken);
i.putExtra("user_id", userIDToken);
i.putExtra("emailID", email_text);
startActivity(i);
而这就是我如何检索它:
SharedPreferences emailLoginSP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
loginEmail = emailLoginSP.getString("prefEmailId", null);
loginUserId = emailLoginSP.getString("prefUserId", null);
loginAccessToken = emailLoginSP.getString("prefAccess_token", null);
到目前为止一切都正常运行。 我再次说明我的问题是当我强制关闭或重启设备时,我会得到空值。我们能把它永久存储在应用程序内存中吗?还是我这里做错了什么?
任何帮助都将不胜感激。
NULL
,看起来您可能有其他问题。您能告诉我们您在哪里遇到了强制关闭吗? - RobinHoodSharedPreferences
将值存储到XML中,因此无论应用程序如何被销毁,它们始终会被保留。https://dev59.com/im025IYBdhLWcg3wNTEV 您使用的存储或检索代码肯定有问题。 - wired00