为什么我的 SharedPreferences 在我开始新的 Activity 时检索不到正确的数据?

Why doesn't my SharedPreferences retrieve the right data when I start a new Activity?

我有两个活动 LoginActivityMainActivity,我从 LoginActivity 验证我的用户。如果用户成功通过身份验证,我将使用 MainActivity 意图调用 startActivity() 。这是 LoginActivity 的样子:

在我的 onCreate() 中,我初始化了我的 SharedPreferences 对象,这些对象被声明为 class:

的字段
 userInfo = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
 editor = userInfo.edit();

然后我在login()方法中处理认证逻辑:

private void login() {


    progressDialog.setIndeterminate(true);
    progressDialog.setMessage("Authenticating...");
    progressDialog.show();

    final String email = emailText.getText().toString();
    final String password = passwordText.getText().toString();


    new android.os.Handler().postDelayed(new Runnable() {

        public void run() {
            ref.authWithPassword(email, password, new Firebase.AuthResultHandler({      

            // User was authenticated successfully
            @Override
            public void onAuthenticated(AuthData authData) {

              @Override
              public void onDataChange(DataSnapshot snapshot) {
              UserSchema user = snapshot.getValue(UserSchema.class);

                // store the user's name and email with our SharedPreferences
                 editor.putString("name", user.getName());
                 editor.putString("email", user.getEmail());
                 editor.apply();
               }  
          });

         // Dismiss the progress dialog shown while authenticating the user
         progressDialog.dismiss();

      // Start the MainActivity
      Intent intent = new Intent(getApplicationContext(), MainActivity.class);
      startActivity(intent); 
      }
    }
      }, 3000);
   }

我也在 MainActivity 中初始化 PreferenceManager onCreate():

  userInfo = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

一开始一切正常,但是当 MainActivity 启动时,所有调用都使用我在 MainActivity returns 中设置的默认值来获取存储的用户信息

=41=]:

  // returns the default value at first
  String s1 = userInfo.getString("name", "name"); 
  String s2 = userInfo.getString("email", "email");

Weird part: If I close the app from my device's recents and relaunch it, the right values of the user's name and email show up correctly.

我不确定,但请尝试使用 editor.commit(); 而不是 editor.apply();,因为提交后它会立即存储数据。

请注意 onDataChange 是一个回调,它不会立即被调用,但 startActivity 会在该回调被触发之前被调用。因此,在数据保存到 SharedPreference.

之前调用 MainActivity

代码应该是这样的

private void login() {
    ...
    // User was authenticated successfully
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        UserSchema user = snapshot.getValue(UserSchema.class);

        // store the user's name and email with our SharedPreferences
        editor.putString("name", user.getName());
        editor.putString("email", user.getEmail());
        editor.apply();

        // Start the MainActivity
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
    } 
}