Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了android – 当应用程序强制关闭或设备重新启动时,共享首选项重置数据大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发一个应用程序,我在其中存储用户名和密码在SharedPreferences中.所有的东西都适合我,存储以及检索值.但我发现当我重启设备或强制关闭app时,SharedPreferences中存储的值会被重置.当我再次启动我的应用程序时,我在SharedPreferences键中获得空值.在这里,我正在做什么来存储值:
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);

到目前为止,所有的事情都很好.
再次说明我的问题,当我强制关闭或重启我的设备时,我得到空值.我们可以将它永久存储在应用程序内存中吗?或者,我在这里做错了什么?

任何帮助将不胜感激.

解决方法

我有一个登录屏幕,希望应用程序看起来好像在应用程序关闭/销毁/电话呼叫等后仍然在内部屏幕上“登录”.

我有一个首选项对象来保存登录注册后的值.我在所有关键屏幕onResume()方法中读取了首选项值.

登录后(例如)

SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("sessionId",application.currentSessionId);
editor.putString("userId",application.currentUserId);
editor.putString("userEmail",application.currentUserEmail);
editor.putString("siteUserId",application.currentSiteUserId);
editor.commit();

在活动的onResume()内:
(即在内部屏幕内)

SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(activity);
application.currentSessionId = app_preferences.getString("sessionId","");
application.currentUserId = app_preferences.getString("userId","");
application.currentUserEmail = app_preferences.getString("userEmail","");
application.currentSiteUserId = app_preferences.getString("siteUserId","");

注意.我有应用程序“全局”变量,即application.currentSessionId,你可以只替换你的变量

尝试类似的东西,也许你没有保存或正确检索值,因为SharePreferences应该工作

大佬总结

以上是大佬教程为你收集整理的android – 当应用程序强制关闭或设备重新启动时,共享首选项重置数据全部内容,希望文章能够帮你解决android – 当应用程序强制关闭或设备重新启动时,共享首选项重置数据所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。