应用程序会在重新启动时忘记共享首选项 [英] App keeps forgetting sharedpreferences on restart
问题描述
我不知道该怎么办
似乎可以在android 3.0及更高版本上正常工作,但是在android 2.3.3上,每次我启动该应用程序时,它都会再次询问用户名/密码.
Seems to be working fine with android 3.0 and higher, but on android 2.3.3 every time I launch the application it is asking for the username/password again.
我正在使用共享的首选项.
I'm using the shared preferences.
这是我保存首选项的方式:
Here is how I save preferences:
SharedPreferences preferences = MyApplication.getAppContext().getSharedPreferences("athopbalance", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username).commit();
editor.putString("password", password).commit();
这是我的阅读方式:
SharedPreferences preferences = MyApplication.getAppContext().getSharedPreferences("athopbalance", Context.MODE_PRIVATE);
String username = preferences.getString("username", "");
String password = preferences.getString("password", "");
我还尝试使用以下代码保存首选项:
I also tried to save preferences using this code:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username).commit();
editor.putString("password", password).commit();
然后使用以下代码阅读它们:
And the read them with this code:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());
String username = preferences.getString("username", "");
String password = preferences.getString("password", "");
但是它也不起作用.
问题是在重新启动应用程序之前,我可以看到它们仍然存在.但是,一旦我重新启动-我最终得到的用户名是"(空字符串),密码是".
The problem is before I restart the application I can see that they are still there. However as soon as I do the restart - I end up with getting "" (empty string) for username and "" for password.
任何想法都将不胜感激
推荐答案
我不知道到底发生了什么,但是重新启动模拟器后问题就消失了.
I don't know exactly what happened, but after I've restarted the emulator issue is gone.
很抱歉浪费您的时间
这篇关于应用程序会在重新启动时忘记共享首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!