gpt4 book ai didi

java - 当我启动新 Activity 时,为什么我的 SharedPreferences 无法检索到正确的数据?

转载 作者:行者123 更新时间:2023-12-01 18:07:07 26 4
gpt4 key购买 nike

我有两个 Activity LoginActivityMainActivity,我从 LoginActivity 验证我的用户。如果用户身份验证成功,我将使用 MainActivity Intent 调用 startActivity()。 LoginActivity 如下所示:

在我的 onCreate() 中,我初始化了已声明为类字段的 SharedPreferences 对象:

 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 的 onCreate() 中初始化 PreferenceManager:

  userInfo = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
<小时/>

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

  // 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.

最佳答案

请注意,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);
}
}

关于java - 当我启动新 Activity 时,为什么我的 SharedPreferences 无法检索到正确的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35539829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com