问题
There's this android application I'm building with Firebase as the backend. It requires two different sets of users, a set of lecturers and a set of students. There's an issue however. I would want a student that has already logged in and closed the app to automatically log in to a different home activity when the student opens the app again. Same should apply to the lecturers. How do I achieve that? Can someone help with a sample code? I know about the functionality that firebase uses to automatically log in users to the homepage of an app but how do I specify the page that should automatically open if one is a student or a lecturer?
My Login Activity
public class LoginActivity extends AppCompatActivity {
private TextInputLayout mLoginEmail;
private TextInputLayout mLoginPassword;
private ProgressDialog mLoginProgress;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference jLoginDatabase, student_token_reference, lecturer_token_reference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mLoginProgress = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
Intent main_intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(main_intent);
}
mLoginEmail = findViewById(R.id.login_email);
mLoginPassword = findViewById(R.id.login_password);
Button mLogin_btn = findViewById(R.id.login_btn);
TextView msignup = findViewById(R.id.sign_up_text);
msignup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent gotosignup = new Intent(LoginActivity.this, ChoiceActivity.class);
startActivity(gotosignup);
}
});
mLogin_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email = mLoginEmail.getEditText().getText().toString();
String password = mLoginPassword.getEditText().getText().toString();
if (!TextUtils.isEmpty(email) || !TextUtils.isEmpty(password)) {
mLoginProgress.setTitle("Logging in user");
mLoginProgress.setMessage("Please wait while we log you in...");
mLoginProgress.setCanceledOnTouchOutside(false);
mLoginProgress.show();
loginUser(email, password);
} else {
Toast.makeText(LoginActivity.this, "Please fill in credentials first", Toast.LENGTH_LONG).show();
}
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
} else {
// User is signed out
}
// ...
}
};
}
private void loginUser(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(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()) {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
String RegisteredUserID = currentUser.getUid();
jLoginDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(RegisteredUserID);
jLoginDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userType = dataSnapshot.child("userType").getValue().toString();
if (userType.equals("Lecturers")) {
mLoginProgress.dismiss();
Intent intentResident = new Intent(LoginActivity.this, LecturerMainActivity.class);
intentResident.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intentResident);
finish();
} else if (userType.equals("Students")) {
mLoginProgress.dismiss();
Intent intentMain = new Intent(LoginActivity.this, MainActivity.class);
intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intentMain);
finish();
} else {
mLoginProgress.hide();
Toast.makeText(LoginActivity.this, "Failed to authenticate user", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
public void onBackPressed() {
moveTaskToBack(true);
super.onBackPressed();
}
}
回答1:
This is a hack I used to solve the same issue. (Please note that this method may have security issues and I prefer using Firebase Custom Claims using Firebase Admin).
Create a LoginActivity
using which you log in the user and after logging in, access the user type(admin, student, staff, paid whatever) in an UserTypeSelectorActivity
and form this activity you can pass the user type to other activities using Intent data or shared preferences (which you feel better according to your app)
public class UserTypeSelectorActivity extends AppCompatActivity {
// Firebase Variables
FirebaseUser firebaseUser;
FirebaseDatabase firebaseDatabase;
DatabaseReference firebaseDatabaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Activity Name", getLocalClassName());
// Initializing Firebase Variables
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
firebaseDatabaseReference = firebaseDatabase.getReference();
if (firebaseUser != null) {
firebaseDatabaseReference.child("my_app_user").child(firebaseUser.getUid())
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Check user type and redirect accordingly
if (dataSnapshot.child("admin").exists()) {
Boolean admin = dataSnapshot.child("admin")
.getValue().toString().equals("true");
if (admin) {
startActivity(new Intent(UserTypeSelectorActivity.this,
AdminActivity.class));
finish();
} else {
startActivity(new Intent(UserTypeSelectorActivity.this,
ClientActivity.class));
finish();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
Note: A precautionary warning that this is not a proper solution. It is how I have implemented in my app.
回答2:
public class LoginActivity extends AppCompatActivity {
private TextInputLayout mLoginEmail;
private TextInputLayout mLoginPassword;
private ProgressDialog mLoginProgress;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference jLoginDatabase, student_token_reference, lecturer_token_reference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mLoginProgress = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
String uid = mAuth.getCurrentUser().getUid();
fDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
fDatabase.addValueEventListener(new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(uid.equals(dataSnapshot.child("key"))
{
// Open Student Activity
}
else
{
// Open Lecturers Activity
}
}
I am unaware of your database collections. So take them appropriately.
回答3:
If you use the FirebaseAuth
+ FirebaseDatabase
you can do it picking the type of the user. So in your model add the String type
attribute. When the user login is not null check:
if(user.getType().equals("student1")){
startActivity(intentStudent1);
} else if(user.getType().equals("student2")){
startActivity(intentStudent2);
}
And the fathers tree of your database will be the email of the student, I use it in my app mayking it in Base64 code/uncode
so the email elaine@gmail.com
will be ZWxhaW5lQGdtYWlsLmNvbQ==
.
I use it to get the status...
来源:https://stackoverflow.com/questions/50534695/how-to-log-in-two-different-types-of-users-to-different-activities-automatically