应用程序在重新启动时不断忘记共享引用



我不知道该怎么处理了

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

但它也不起作用。

问题是在我重新启动应用程序之前,我可以看到它们仍然存在。然而,一旦我重新启动,我就会得到"(空字符串(作为用户名,"作为密码。

任何想法都将不胜感激

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)

试试这个:

 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;

您有两个选项:

  1. 在活动的生命周期中获得共享的偏好值。

  2. .commit 之前调用.clear

看看我的答案:

重新启动Android 后自定义小工具中的Android持久可检查菜单

我不知道到底发生了什么,但在我重新启动后,模拟器问题就消失了。

很抱歉浪费您的时间

最新更新