How to signout a user from the app in android - java

I'm new to android and now I'm working on making users to login using their facebook and gmail things going well but i need to know how do make the user to signout from the app and login in the user with new accounts. i tried a lot of tutorials but none of them are not as i thought and expected. The user when clicks on logout button from another activity and comebacks to login activity.
example: when user logins from UserAction.class the logout button is in ProfileFragment.class
I tried a lot but haven't found any solution any help.
Code i Tried
public class UserAction extends AppCompatActivity {
private CallbackManager callbackManager;
public LoginButton loginButton;
private static final String EMAIL = "email";
private SignInButton signInButton;
GoogleSignInClient mGoogleSignInClient;
private FirebaseAuth mAuth;
private int RC_SIGN_IN = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_action);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
signInButton = findViewById(R.id.gmail_login_button);
mAuth = FirebaseAuth.getInstance();
GoogleSignInOptions gsp = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gsp);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GmailLogin();
}
private void GmailLogin() {
Intent mailSignIn = mGoogleSignInClient.getSignInIntent();
startActivityForResult(mailSignIn,RC_SIGN_IN);
}
});
AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
AppEventsLogger.activateApp(getApplication());
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.fb_login_button);
loginButton.setReadPermissions(Arrays.asList(EMAIL));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Intent intent = new Intent(UserAction.this, AppMain.class);
startActivity(intent);
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN){
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void handleSignInResult(Task<GoogleSignInAccount> CompletedTask) {
try {
GoogleSignInAccount account = CompletedTask.getResult(ApiException.class);
Toast.makeText(this, "Signed in Successfully", Toast.LENGTH_SHORT).show();
FirebaseGoogleAuth(Objects.requireNonNull(account));
} catch (ApiException e) {
ConstraintLayout UserAction = findViewById(R.id.userAction);
Snackbar snackbar = Snackbar.make(UserAction,"Login Failed Please try Again.", Snackbar.LENGTH_SHORT);
snackbar.show();
FirebaseGoogleAuth(null);
}
}
private void FirebaseGoogleAuth(final GoogleSignInAccount account) {
AuthCredential authCredential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(authCredential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
FirebaseUser user = mAuth.getCurrentUser();
GoogleSignInAccount googleSignInAccount = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
String personName = Objects.requireNonNull(googleSignInAccount).getDisplayName();
String personEmail = googleSignInAccount.getEmail();
String personId = googleSignInAccount.getId();
Toast.makeText(UserAction.this, personName+ "\n" +personEmail + "\n" + personId , Toast.LENGTH_SHORT).show();
}
}
});
}
}

To sign out from Firebase use
mAuth.signOut();
And to sign out from google client use
mGoogleSignInClient.signOut()

Related

Trying to implement Facebook Login using Firebase on Android Studio. Screen is stuck loading facebook login page when i try to sign in

i'm a beginner who is learning how to use Android studio and this is my first time posting on Stack Overflow. I wish to implement Facebook login on my android app. I mostly followed this tutorial (https://www.youtube.com/watch?v=ImbuK35vmzs&t=1540s) to create the sign in using facebook.
While I'm able to run the app, ,whenever i click on the sign in using facebook button, the chrome browser opens up and the screen is stuck loading the facebook sign in page (refer to the screenshot). No error pops up on logcat, i've already enabled internet permission in the android manifest file as well as check to see the facebook access id + secret key were correctly copied. Below is my MainActivity.java code. Any idea why this issue might be happening and how do i go about troubleshooting it? Thank you.
Facebook Login Stuck:
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mFirebaseAuth;
private CallbackManager mCallbackManager;
private TextView textViewUser;
private LoginButton loginButton;
private ImageView mLogo;
private FirebaseAuth.AuthStateListener authStateListener;
private AccessTokenTracker accessTokenTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
Button registerButton = findViewById(R.id.signupButton);
textViewUser = findViewById(R.id.textView_user);
mFirebaseAuth = FirebaseAuth.getInstance();
//Initialise facebook SDK
FacebookSdk.sdkInitialize(getApplicationContext());
//Assign textviewuser to the facebook button
mLogo = findViewById(R.id.image_logo);
loginButton = findViewById(R.id.facebook_button);
// Requesting read permission for the email and profile for facebook login
loginButton.setReadPermissions("email","public_profile");
mCallbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "onSuccess" + loginResult);
handleFacebookToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "onCancel");
}
#Override
public void onError(#NonNull FacebookException error) {
Log.d(TAG, "onError" + error);
}
});
authStateListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
updateUI(user);
} else {
updateUI(null);
}
}
};
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null){
mFirebaseAuth.signOut();
}
}
};
private void handleFacebookToken(AccessToken token) {
Log.d(TAG, "handleFacebookToken" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mFirebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Log.d(TAG, "sign in with credential: successful");
FirebaseUser user = mFirebaseAuth.getCurrentUser();
updateUI(user);
}else{
Log.d(TAG, "sign in with credential: failure", task.getException());
Toast.makeText(MainActivity.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
mCallbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
private void updateUI(FirebaseUser user) {
if (user != null) {
textViewUser.setText(user.getDisplayName());
if(user.getPhotoUrl()!=null){
String photoUrl= user.getPhotoUrl().toString();
photoUrl = photoUrl + "?type=large";
Picasso.get().load(photoUrl).into(mLogo);
}
}
else{
textViewUser.setText("");
mLogo.setImageResource((R.drawable.logo));
}
}
public void toastMsg(String message){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}
#Override
protected void onStart(){
super.onStart();
mFirebaseAuth.addAuthStateListener((authStateListener));
}
#Override
protected void onStop(){
super.onStop();
if(authStateListener!=null){
mFirebaseAuth.removeAuthStateListener(authStateListener);
}
}
}

Sign In Google with Android not working error while connecting

Hi i am having a problem with my the google connexion. Every time that the code is executed it goes in to the catch. I dont know why. I followed the steps from the Google tutorial and saw manyq questions related to that on stack but still not help me to solve this issue. Whe the code is runned it goes in to the catch and it shows the toast that i made. " error while .. ".
Here is what it looks like. I am posting the whole code for the authentification so everyone can analyze it and give me a solution if possible .
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient= GoogleSignIn.getClient(this,gso);
signInButton=(SignInButton)findViewById(R.id.googleButton);
signInButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
//pour google
mAuthStateListener=new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser mFireBaseUser=mFirebaseAuth.getCurrentUser();
if(mFireBaseUser != null){
Toast.makeText(LoginActivity.this,"you are logged in",Toast.LENGTH_SHORT).show();
Intent i= new Intent(LoginActivity.this, PrayersEvents.class);
startActivity(i);
}
else{
Toast.makeText(LoginActivity.this,"please login",Toast.LENGTH_SHORT).show();
}
}
};
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email=emailId.getText().toString();
String pwd=password.getText().toString();
if (email.isEmpty()) {
emailId.setError("Please enter email");
emailId.requestFocus();
}
else if(pwd.isEmpty()){
password.setError("Please enter your password");
password.requestFocus();
}
else if(email.isEmpty() || pwd.isEmpty()){
Toast.makeText(LoginActivity.this,"Fields are empty!",Toast.LENGTH_SHORT).show();
}
else if(!(email.isEmpty() && pwd.isEmpty())){
mFirebaseAuth.signInWithEmailAndPassword(email,pwd).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(LoginActivity.this,"Login error!",Toast.LENGTH_SHORT).show();
}
else{
Intent intoHome=new Intent(LoginActivity.this, PrayersEvents.class);
startActivity(intoHome);
}
}
});
}
else{
Toast.makeText(LoginActivity.this,"Error ocurred!",Toast.LENGTH_SHORT).show();
}
}
});
tvSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intoSignUp=new Intent(LoginActivity.this,MainActivity.class);
startActivity(intoSignUp);
}
});
}
#Override
protected void onStart() {
super.onStart();
GoogleSignInAccount account=GoogleSignIn.getLastSignedInAccount(this);
if(account !=null){
startActivity(new Intent(LoginActivity.this, CreateEvent.class));
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
Log.d("MON_TAG", account.toString());
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Toast.makeText(getApplicationContext(),"error while logging in",Toast.LENGTH_SHORT).show();
Log.w("errorMsg","Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {//acct means account
Log.d("MON_TAG", "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mFirebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("MON_TAG", "signInWithCredential:success");
FirebaseUser user = mFirebaseAuth.getCurrentUser();
startActivity(new Intent(LoginActivity.this, CreateEvent.class));
Toast.makeText(getApplicationContext(),"You are now connected",Toast.LENGTH_SHORT).show();
} else {
GoogleSignInAccount account=GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if(account !=null){
startActivity(new Intent(LoginActivity.this, CreateEvent.class));
}
// If sign in fails, display a message to the user.
Toast.makeText(getApplicationContext(),"Could not log in user",Toast.LENGTH_SHORT).show();
}
}
});
}
I think you didn't instanciate the GoogleApiClient object..
try this code .. it worked for me ..
//a constant for detecting the login intent result
private static final int RC_SIGN_IN = 234;
//Tag for the logs optional
private static final String TAG = "YoussefIslem";
//creating a GoogleSignInClient object
GoogleSignInClient mGoogleSignInClient;
GoogleApiClient googleApiClient;
CallbackManager mCallbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.web_client_id))
.requestEmail()
.build();
googleApiClient =new GoogleApiClient.Builder(this)
.enableAutoManage(this,this)
.addApi(Auth.GOOGLE_SIGN_IN_API,gso)
.build();
//Then we will get the GoogleSignInClient object from GoogleSignIn class
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
findViewById(R.id.googleContinue).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
//getting the auth credential
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
//Now using firebase we are signing in the user here
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(MainActivity.this, "User Signed In", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
finish();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
//this method is called on click
private void signIn() {
//getting the google signin intent
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
googleApiClient.clearDefaultAccountAndReconnect();
//starting the activity for result
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//if the requestCode is the Google Sign In code that we defined at starting
if (requestCode == RC_SIGN_IN) {
//Getting the GoogleSignIn Task
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
//Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
//authenticating with firebase
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
Toast.makeText(MainActivity.this,"I'm here"+ e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}

How to add a cancel button for google signIn accountPicker dialog box in android

I am new to android. I am trying to make an android application with authentication by google signIn using firebase. I want to add an additional button to the google signIn accountPicker. This is my code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
GoogleSignInClient mGoogleSignInClient;
private int RC_SIGN_IN = 1;
private FirebaseAuth mAuth;
android.app.AlertDialog Dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(MainActivity.this, gso);
signIn();
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(getApplicationContext() , "Authentication failed" , Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
}
private void updateUI(FirebaseUser user) {
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if (acct != null) {
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
Toast.makeText(getApplicationContext() , "Name = "+ personName , Toast.LENGTH_SHORT).show();
}
}
}
Here is the accountpicker dialog of the google signIn.
I need to add an additional (Cancel)button in this dialog.
Is there a way to do this?

Facebook Login Button work but doesn't sign in successfully

I am using facebook login in my app when I press the button it works as normal after I press On continue as (UserName) nothing happens at all the app is connected to firebase I have added two toasts to check if the signing in process failed or not but none of them appear at all neither the toast that should appear when it failed nor the other toast that should appear when it works
this is my activity code :
public class GeneralSignActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
SignInButton button;
private final static int RC_SIGN_IN = 2;
private final String TAG = "Logging";
CallbackManager mCallbackManager;
GoogleApiClient mGoogleApiClient;
GoogleSignInOptions gso;
private GoogleSignInClient mGoogleSignInClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_general_sign);
ButterKnife.bind(this);
mAuth = FirebaseAuth.getInstance();
button = findViewById(R.id.googleBtn);
FacebookSdk.sdkInitialize(getApplicationContext());
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(GeneralSignActivity.this, "حدث خطأ برجاء اعادة المحاولة", Toast.LENGTH_SHORT).show();
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API)
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = findViewById(R.id.facebookBtn);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
Toast.makeText(GeneralSignActivity.this, "نجح تسجيل الدخول", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
// ...
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
// ...
}
});
}
private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
Intent i = new Intent(GeneralSignActivity.this, MainActivity.class);
startActivity(i);
Toast.makeText(GeneralSignActivity.this, "handle facebook access token.",
Toast.LENGTH_SHORT).show();
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(GeneralSignActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
// updateUI(null);
}
// ...
}
});
}
#OnClick(R.id.btnSignUp)
void click(View view) {
Intent i = new Intent(this, SignUpActivity.class);
startActivity(i);
}
#OnClick(R.id.btnSignIn)
void click2(View view) {
Intent i = new Intent(this, SignInActivity.class);
startActivity(i);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
Toast.makeText(this, "نجح تسجيل الدخول",Toast.LENGTH_SHORT).show();
startActivity(new Intent(GeneralSignActivity.this,MainActivity.class));
} catch (ApiException e) {
Toast.makeText(GeneralSignActivity.this, "حدث خطأ أثناء محاولة التسجيل برجاء اعادة المحاولة", Toast.LENGTH_SHORT).show();
}
}//TODO
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = mAuth.getCurrentUser();
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Toast.makeText(GeneralSignActivity.this, "Authentication Failed.", Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
startActivity(new Intent(GeneralSignActivity.this, MainActivity.class));
}
}
}

I want to retrieve current logged in user data from firestore but it shows blank where I want to show my data

I am trying to get the current logged in user from the google firestore database
and i saw this same problem in stackoverflow of a user and i used that same method but showing blank in place user details.
Please help me Thanks.
I am earlier using querysnapshot as it gives all the users.
image description here
the image for database is
enter image description here
The code is:
public class UserProfile extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int GALLERY_INTENT = 2;
private static final String TAG = "UserProfile";
String UserId;
FirebaseAuth auth;
ImageButton Photo;
ImageView photoview;
TextView name, email, password, phone;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
if(getSupportActionBar()!=null ){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
DatabaseReference Database = FirebaseDatabase.getInstance().getReference("users");
DatabaseReference DBRef = Database.child("users");
auth = FirebaseAuth.getInstance();
UserId = auth.getCurrentUser().getUid();
FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();
StorageReference mStorage = FirebaseStorage.getInstance().getReference();
FirebaseStorage storage = FirebaseStorage.getInstance();
photoview = (ImageView)findViewById(R.id.photoview);
Photo = (ImageButton)findViewById(R.id.Photoedit);
name = (TextView)findViewById(R.id.username);
email = (TextView)findViewById(R.id.useremail);
password = (TextView)findViewById(R.id.password1);
phone = (TextView)findViewById(R.id.userPhone);
mFirestore.collection("users").document(UserId).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String Name = documentSnapshot.getString("Name");
String Email = documentSnapshot.getString("Email");
String Password = documentSnapshot.getString("Password");
String Phone = documentSnapshot.getString("Phone Number");
name.setText(Name);
email.setText(Email);
password.setText(Password);
phone.setText(Phone);
}
});
Photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(UserProfile.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_INTENT);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
photoview.setImageBitmap(photo);
} else if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image ", picturePath + "");
photoview.setImageBitmap(thumbnail);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
Intent i = new Intent(UserProfile.this,category.class);
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
}
My database structure is
Ramiki(my app name)
So here it is
Ramiki --> users(collection)--> SiQEIDaQJfUBqZBBt1eo(document uid)----> fields(Email, Name, Password, Phone Number).
Well sorry i am not able to give screenshort because i am not allowed by stack overflow 10 points needed.
And my code for writing data in firestore is
public class LoginActivity extends AppCompatActivity implements View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LoginActivity";
private TextInputEditText textInputEditTextName;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private TextInputEditText textInputEditTextConfirmPassword;
private TextInputEditText textInputEditTextPhone;
private AppCompatButton appCompatButtonRegister;
private AppCompatTextView appCompatTextViewLoginLink;
private FirebaseAuth auth;
private ProgressBar progressBar;
private static final int RC_SIGN_IN = 1;
private GoogleApiClient mGoogleApiClient;
private SignInButton btnSignIn;
private FirebaseFirestore mFirebaseFirestore;
private FirebaseAuth.AuthStateListener authListener;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
mFirebaseFirestore = FirebaseFirestore.getInstance();
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(true)
.build();
mFirebaseFirestore.setFirestoreSettings(settings);
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
}
};
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignIn.setOnClickListener(this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Customizing G+ button
btnSignIn.setSize(SignInButton.SIZE_STANDARD);
btnSignIn.setScopes(gso.getScopeArray());
appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
appCompatTextViewLoginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(LoginActivity.this, account.class);
startActivity(i);
finish();
}
});
//if the user is already logged in we will directly start the category activity
if (SavesharedPreferences.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, category.class));
finish();
return;
}
findViewById(R.id.appCompatButtonRegister).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Name = textInputEditTextName.getText().toString().trim();
String Email = textInputEditTextEmail.getText().toString().trim();
String Password = textInputEditTextPassword.getText().toString().trim();
String Phone_Number = textInputEditTextPhone.getText().toString().trim();
String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
progressBar.setVisibility(View.VISIBLE);
// Create a new user with a first and last name
Map<String, Object> user = new HashMap<>();
user.put("Name", Name);
user.put("Email", Email);
user.put("Password", Password);
user.put("Phone Number", Phone_Number);
if (TextUtils.isEmpty(Name)) {
textInputEditTextName.setError("Please enter name");
textInputEditTextName.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (TextUtils.isEmpty(Email)) {
textInputEditTextEmail.setError("Please enter your email");
textInputEditTextEmail.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
textInputEditTextEmail.setError("Email already exist");
textInputEditTextEmail.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (TextUtils.isEmpty(Password)) {
textInputEditTextPassword.setError("Enter a password");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if(Password.length() < 7){
textInputEditTextPassword.setError("Paasword must be greater than 7 digits");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (!textInputEditTextPassword.getText().toString().equals(textInputEditTextConfirmPassword.getText().toString())) {
textInputEditTextPassword.setError("Password Doesn't Match");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else {
// Add a new document with a generated ID
mFirebaseFirestore.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
registerUser();
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
}
}
});
initViews();
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.btn_sign_in:
signIn();
break;
}
}
private void registerUser() {
final String Name = textInputEditTextName.getText().toString().trim();
final String Email = textInputEditTextEmail.getText().toString().trim();
final String Password = textInputEditTextPassword.getText().toString().trim();
final String Phone_Number = textInputEditTextPhone.getText().toString().trim();
final String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
//first we will do the validations
if (TextUtils.isEmpty(Name)) {
textInputEditTextName.setError("Please enter name");
textInputEditTextName.requestFocus();
return;
}
if (TextUtils.isEmpty(Email)) {
textInputEditTextEmail.setError("Please enter your email");
textInputEditTextEmail.requestFocus();
return;
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
textInputEditTextEmail.setError("Email already exist");
textInputEditTextEmail.requestFocus();
return;
}
if (TextUtils.isEmpty(Password)) {
textInputEditTextPassword.setError("Enter a password");
textInputEditTextPassword.requestFocus();
return;
}
if(Password.length() < 7 ) {
textInputEditTextPassword.setError("Paasword must be greater than 7 digits");
textInputEditTextPassword.requestFocus();
return;
}
if (TextUtils.isEmpty(ConfirmPassword)) {
textInputEditTextPassword.setError("Password Doesn't Match");
textInputEditTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(Email, Password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(LoginActivity.this, "Register Successful " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()){
sendEmailVerification();
}
// 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.
else if (!task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, "Nothing Happens", Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendEmailVerification() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(LoginActivity.this,"Please Check Your Email For Verification",Toast.LENGTH_LONG).show();
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(LoginActivity.this, account.class));
finish();
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
progressBar.setVisibility(View.GONE);
}
private void initViews() {
textInputEditTextName = (TextInputEditText) findViewById(R.id.textInputEditTextName);
textInputEditTextEmail = (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword = (TextInputEditText) findViewById(R.id.textInputEditTextPassword);
textInputEditTextPhone = (TextInputEditText) findViewById(R.id.textInputEditTextPhone);
appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
textInputEditTextConfirmPassword = (TextInputEditText) findViewById(R.id.textInputEditTextConfirmPassword);
appCompatButtonRegister = (AppCompatButton) findViewById(R.id.appCompatButtonRegister);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(LoginActivity.this, "You Got an Error",Toast.LENGTH_LONG).show();
}
protected void onStart(){
super.onStart();
auth.addAuthStateListener(authListener);
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = auth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
}
This unique id SiQEIDaQJfUBqZBBt1eo is generated when you are adding the user as a Map or when you are using a call to document() method without passing an argument.
In order to solve this, there are two ways. One would be to create a model class (UserModel), then create an object of that class and in the end get the uid of the user once it authenticated and add the object to the database like this:
String Name = textInputEditTextName.getText().toString().trim();
String Email = textInputEditTextEmail.getText().toString().trim();
String Password = textInputEditTextPassword.getText().toString().trim();
String Phone_Number = textInputEditTextPhone.getText().toString().trim();
String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
UserModel userModel = new UserModel(Name, Email, Password, Phone_Number, ConfirmPassword);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
usersRef.document(uid).set(userModel);
See, I have passed the uid as argument to the document() method.
The second approach would be to pass no argument to the document() method but to store that key into a variable like this:
String key = usersRef.document().getKey();
usersRef.document(key).set(userModel);
Edit:
There also another method, which I recommend you use it. Instead of using this line of code:
mFirebaseFirestore.collection("users")
.add(user)
.addOnSuccessListener(/* ... */)
Use the following line of code:
mFirebaseFirestore.collection("users")
.document(uid)
.set(user)
.addOnSuccessListener(/* ... */)
Remove the old data, add fresh one and your problem will be solved.

Categories