应用程序重新启动时忘记共享首选项

7

我不知道该怎么办了。

似乎在安卓3.0及以上版本上运行良好,但在安卓2.3.3上每次启动应用程序都会再次要求输入用户名/密码。

我正在使用共享首选项。

以下是我保存首选项的方式:

        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", "");

我也尝试使用这段代码保存偏好设置:
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("username", username).commit();
        editor.putString("password", password).commit();

并使用以下代码进行阅读:

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());
    String username = preferences.getString("username", "");
    String password = preferences.getString("password", "");

但它仍然不起作用。
问题是在重新启动应用程序之前,我可以看到它们仍然存在。但是一旦我重启,用户名变成了空字符串"",密码也变成了空字符串""。
如有任何想法,将不胜感激。
4个回答

2
public class MyApplication extends Application {
    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate() called");
    }

    public MyApplication() {
        super();
        Log.d(TAG, "Constructor called");
        instance = this;
    }


    public static MyApplication getApplication() {
        if (instance == null) {
            instance = new MyApplication();
        }
        return instance;
    }
}

使用方法:

MyApplication.getApplication().getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE)

你的示例在返回之前没有将 new MyApplication 保存到实例中,因此缓存永远不会发生。 - mikebabcock

1

1

试试这个:

 SharedPreferences preferences = context.getSharedPreferences("YOUR_TAG", 0);
 String username = preferences.getString("username", "");
 String password = preferences.getString("password", "");


  SharedPreferences.Editor editor = preferences.edit();
    editor.putString("username", username).commit();
    editor.putString("password", password).commit();

其中 context 是您的应用程序的上下文:

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


        context = this;

嗨,非常感谢您的评论。在我的第一个示例中,我正在做相同的事情,但恐怕它不起作用。 - Allan Spreys
请使用您的活动而不是MyApplication进行尝试。 - Gyonder
我之前调用了getApplicationContext(),而没有从活动中传递上下文。 - Alberto M

0

我不知道发生了什么事情,但是在我重新启动模拟器后问题已经解决了。

很抱歉浪费了您的时间。


我也遇到了同样的问题,重启后就像你的一样消失了。真的很奇怪... - Victor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接