我可以将SharedPreference
放在我的工作进度论文项目中。我在这里遇到一个简单的麻烦。这是我的loginActivity
的示例代码我仍然想知道如何/在哪里放置其他SharedPreference代码。
我在使用SharedPreference进行一次登录时遇到问题。我不知道我在哪里放置代码。我通过网络搜索但没有任何作品对我来说我知道我无法放置代码但我无法解决它。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.prgBar);
btnLogin = findViewById(R.id.user_login);
userEmail = findViewById(R.id.user_email);
userPwd = findViewById(R.id.user_password);
btnReg = findViewById(R.id.user_reg);
btnReg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = userEmail.getText().toString();
final String password = userPwd.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
userPwd.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, userInterface.class);
startActivity(intent);
finish();
}
}
});
}
});
}
}
答案 0 :(得分:1)
由于您使用的是Firebase身份验证,因此无需使用SharedPreferences
查看用户之前是否已登录。
您可以执行此操作,例如Splash Activity //first activity
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
if(user!=null){
//Signed in, go to home activity
Intent i=new Intent(SplashActivity.this,HomeActivity.class);
startActivity(i);
}
else{
//not logged in
Intent intent=new Intent(SplashActivity.this,LoginActivity.class);
startActivity(intent);
}