In one activity, I am signing in the user, and it moves on to another activity where the user is greeted. I am using the built-in Firebase methods for signing in a user using email/password. I have the UID in Firebase Database and this is linked with a name. I am just manually inputting users in Firebase and will implement a sign up activity later. How do I access the UID of the user in the second activity?
Alternatively to passing the uid around, you can use an auth state listener to detect the user in each activity. From that documentation page:
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
This code would typically go into a base-class that you derive your activities from.
just use
FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String UID = user.getUid();
It will automatically get user from previous acivity.
You should either save it in SharedPreferences and retrieve it in the second activity or pass it into the second Activity via the Intent object.
SharedPreferences is one of the simpler ways to store data persistently in the app. Data stored in SharedPreferences can be retrieved and modified from almost anywhere in the app. Data will survive phone restarts, and even an app uninstall, because it can be backed up by the system. Here is the official explanation. And here is a good tutorial.
Related
I signed up as new User and FirebaseAuth.getInstance().getCurrentUser() returned correctly the logged in user. Both in onCreate() and onStart() methods.
Then, I removed that user from the Firebase Authentication console. I was expecting to have FirebaseAuth.getInstance().getCurrentUser() = null. But it still returns the user that I have removed. Both in onCreate() and onStart() methods.
How is it possible?
You need to attach a listener to the AuthState, try this:
//Declaration and defination
private FirebaseAuth firebaseAuth;
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null){
//Do anything here which needs to be done if user is null
}
else {
}
}
};
//Init and attach
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.addAuthStateListener(authStateListener);
}
Deleting a user in the console does not instantly notify any client apps where that user might be signed in. From the client app's perspective, there is still a user with a user ID and an auth token. But that auth token will no longer be able to work with data in Realtime Database, Cloud Firestore, and Cloud Storage protected by user-based security rules. The token will also no longer validate with the Firebase Admin SDK. These actions you can check for failure. Firebase Auth will eventually try to refresh the token within an hour, which will fail, and the user will be signed out.
My app works with Firebase Authentication. And when user starts app I need to add new user in Firebase, but I have 3 state:
There is no account
There is an account, but the user signed out
There is an account and the user signed in
For these 3 states, I must do the next:
create account in Firebase + log in my Database (at the same time)
then sign in Firebase
sign in Firebase + log in my Database (at the
same time)
log in my Database
How to make the first item correctly using Tasks? How to control errors?
I determine whether the signed user or not, using:
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
firebaseAuthUser = true;
} else {
// User is signed out
firebaseAuthUser = false;
}
}
};
You can use FirebaseUI-Android to gracefully handle those situations for you.
It's really simple to implement! Please check it here.
You can check all FirebaseUI features here
How to identify the id (from push) of existing user?
I created a node using push when a user is registered, but when the user try to login again, I don't know how to identify it directly because its a different key.
Is it wrong to use push instead of the authentication id as my node? Because I want to retrieve the data I kept in my db for that user.
// [START auth_state_listener]
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) { //I WANT TO RETRIEVE DB DATA HERE
You ask: Is it wrong to use push instead of the authentication id as my node? The answer is almost certainly, yes. The documentation for FirebaseUser.getUid() states:
Returns a string used to uniquely identify your user in your Firebase
project's user database. Use it when storing information in Firebase
Database or Storage, or even in your own backend
The completion of the code in your post would be something like:
if (user != null) {
DatabaseReference ref = FirebaseDatabase.getInstance()
.getReference("users").child(user.getUid());
ref.addListenerForSingleValueEvent(...);
}
Can any one tell me that what does get Current User do?
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
progressDialog = new ProgressDialog(this);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() != null){
//start profile activity
finish();
startActivity(new Intent(getApplicationContext(),Profile.class));
}
I am confused on which user get Current User pick?
FirebaseAuth.getInstance().getCurrentUser() returns the currently logged in user in firebase. The user which whith whom the credentials you made the login from your android emulator. If a user isn't signed in, getCurrentUser returns null.
firebaseAuth.getCurrentUser() is used get a FirebaseUser object, which contains information about the signed-in user.
If it returns null the user has not signed in else it will be redirected to Profile.class...(In your above code)
I'm developing a small android app, and basically so far it just has login and logout functionality. I'm using Firebase to store user data and also for authentication.
So I have login working and it authenticates users as it should and I have logging out working in the sense that it unauthenticates users. But is there anything I have to do from within the app to kill the session?
if (id == R.id.action_log_out) {
ref.unauth(); //End user session
startActivity(new Intent(MainActivity.this, LoginActivity.class)); //Go back to home page
finish();
}
Will this work as I think it should? Obviously if someone logs out they shouldn't be able to hit th back button and magically go back to the last page without re-logging in.
From Firebase docs
https://firebase.google.com/docs/auth/android/custom-auth
call this FirebaseAuth.getInstance().signOut();
When Firebase authenticates the user (or you authenticate the user with Firebase), it stores the token for that user in local storage on your device. This happens when you call one of the authWith... methods (of course only if it successfully authenticates the user).
Calling ref.unauth(); immediately deletes that token from local storage.
A properly implemented flow would not automatically re-authenticate them when the user presses the back button, but that depends on the flow you implement (which is missing from your question and would likely be too much code anyway).
I see 2 options for the issue we have with the back-Button after Logout:
In your LoginActivity, wich should be you launcher activity, Override onBackPressed Method and leave it empty:
#Override
public void onBackPressed() {
// empty so nothing happens
}
Or/and you can add the LoginActivityIntent in your LogoutActivty if user == null.
This way, whenever a not authenticated user lands on the activity, it will redirect to the LoginActivity instantly, although this looks kinda weird.
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG,"onAuthStateChanged:signed_out");
startActivity(new Intent(LogoutActivity.this, LoginActivity.class));
}
// ...
}
};
First Option is easier, but I guess if you apply both your on the save side ^^ Im coding for 2 weeks now so correct me if im wrong.
You can replace finish() with finishAffinity();
Delete tokens and Instance IDs
String authorizedEntity = PROJECT_ID;
String scope = "GCM";
FirebaseInstanceID.getInstance(context).deleteToken(authorizedEntity,scope);
You can also delete the Instance ID itself, including all associated tokens. The next time you call getInstance() you will get a new Instance ID:
FirebaseInstanceID.getInstance(context).deleteInstanceID();
String newIID = InstanceID.getInstance(context).getId();
private void sendToLogin() { //funtion
GoogleSignInClient mGoogleSignInClient ;
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(getBaseContext(), gso);
mGoogleSignInClient.signOut().addOnCompleteListener(/*CURRENT CLASS */.this,
new OnCompleteListener<Void>() { //signout Google
#Override
public void onComplete(#NonNull Task<Void> task) {
FirebaseAuth.getInstance().signOut(); //signout firebase
Intent setupIntent = new Intent(getBaseContext(), /*To ur activity calss*/);
Toast.makeText(getBaseContext(), "Logged Out", Toast.LENGTH_LONG).show(); //if u want to show some text
setupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(setupIntent);
finish();
}
});
}
this code is written to work as copy past just read COMMENTS in code to customize it to ur needs, i prefer to send user to login