我正在尝试为我的应用程序完成登录屏幕的实现。我有一个REST API后端,用于验证用户名+令牌并返回登录到应用程序的人员的userId。 我想存储已登录应用程序的用户的最后一个userId。我计划使用共享偏好设置。
基于最后存储的userId,我计划执行去主活动(如果此用户先前已登录,但在一段时间后退出并重新登录),或执行AsynkTask以同步某些来自后端的数据(如果是新用户)。这是我的逻辑,似乎无法正常工作。
它正在直接切换到MainSyncTask,即使我使用最后一个用户名登录(userId是相同的,从API接收),savedUserId.equals(currentUserId)应该返回true并执行Intent。最后一个userId正确存储在sharedpreferences db中,请与Stecho一起检查。
String userId = getUserIdFromAPIResponse();
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
private void checkIdAndGoToActivity() {
final String PREF_VERSION_CODE_KEY = "user_id";
// Get current version code
String currentUserId = userId;
// Get saved version code
String savedUserId = sharedpreferences.getString(PREF_VERSION_CODE_KEY, "");
if (savedUserId.equals(currentUserId)) {
Log.e(TAG, "Current User Logged in");
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
/* destroys activity , prevents user from going back to previous MainActivity after login out */
finish();
} else if (!savedUserId.equals(currentUserId)) {
Log.e(TAG, "New user logged in");
MainSyncTask mainSyncTask = new MainSyncTask(LoginActivity.this, LoginActivity.this, userEmail, userPassword);
mainSyncTask.execute();
SyncEventReceiver.setupAlarm(getApplicationContext());
}
// Update the shared preferences with the current version code
sharedpreferences.edit().putString(PREF_VERSION_CODE_KEY, currentUserId).apply();
}