0

I created two activites one LoginActivity and other MainActivity where I want to get user data to be shown like name and photos, then I want user to log out from MainActivity as well. I made a google sign in button from a tutorial where login, logout and userdata was shown in same activity. Now I know I have to put explicit intent on (if login is successful) but I don't know how do I carry userdata like emailID, name(at least), photo to next activity where I use them and update using updateUI method which updated the user details previously in the same Login activity.

My login activity

public class LoginActivity extends AppCompatActivity {

static final int GOOGLE_SIGN_IN = 123;
FirebaseAuth mAuth;
Button btn_login, btn_logout;
TextView text;
ImageView image;
ProgressBar progressBar;
GoogleSignInClient mGoogleSignInClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    btn_login = findViewById(R.id.login);
    btn_logout = findViewById(R.id.logout);
    text = findViewById(R.id.text);
    image = findViewById(R.id.image);
    progressBar = findViewById(R.id.progress_circular);

    mAuth = FirebaseAuth.getInstance();

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    btn_login.setOnClickListener(v -> SignInGoogle());
    btn_logout.setOnClickListener(v -> Logout());

    if (mAuth.getCurrentUser() != null) {
        FirebaseUser user = mAuth.getCurrentUser();
        updateUI(user);
    }
}

public void SignInGoogle() {
    progressBar.setVisibility(View.VISIBLE);
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, GOOGLE_SIGN_IN);
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d("TAG", "firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, task -> {
                if (task.isSuccessful()) {
                    progressBar.setVisibility(View.INVISIBLE);

                    Log.d("TAG", "signInWithCredential:success");

                    FirebaseUser user = mAuth.getCurrentUser();
                    updateUI(user);
                } else {
                    progressBar.setVisibility(View.INVISIBLE);

                    Log.w("TAG", "signInWithCredential:failure", task.getException());

                    Toast.makeText(LoginActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }
            });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GOOGLE_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            GoogleSignInAccount account = task.getResult(ApiException.class);
            if (account != null) firebaseAuthWithGoogle(account);
        } catch (ApiException e) {
            Log.w("TAG", "Google sign in failed", e);
        }
    }
}

private void updateUI(FirebaseUser user) {
    if (user != null)
    {
        String name = user.getDisplayName();
        String email = user.getEmail();
        String photo = String.valueOf(user.getPhotoUrl());
        for (UserInfo userInfo : user.getProviderData())
            if (name == null && userInfo.getDisplayName() != null)
                name = userInfo.getDisplayName();
        text.append("Info : \n");
        text.append(name + "\n");
        text.append(email);
        Picasso.get().load(photo).into(image);
        btn_logout.setVisibility(View.VISIBLE);
        btn_login.setVisibility(View.INVISIBLE);
    } else
    {
        text.setText("Distress Alert\n");
        btn_logout.setVisibility(View.INVISIBLE);
        btn_login.setVisibility(View.VISIBLE);
        Picasso.get().load(R.drawable.ic_firebase_logo).into(image);

    }
}


private void Logout()
{
    FirebaseAuth.getInstance().signOut();
    mGoogleSignInClient.signOut().addOnCompleteListener(this,
            task -> updateUI(null));
}

}

1 Answers1

1

I do not have commenting privileges as of yet, but a simple google search for passing data between activities would have given you this.

How do I pass data between Activities in Android application?

Also, using Intent in this case would not be a good solution, as you're already using Firebase for authentication, you can get the current FirebaseUser in next Activity.

Declare an instance (class variable)

private FirebaseAuth mAuth;

In onCreate() initialize mAuth

mAuth = FirebaseAuth.getInstance();

In onStart() check if the user is signed in and check for null

@Override
public void onStart() {
    super.onStart();
    FirebaseUser currentUser = mAuth.getCurrentUser();
    if (currentUser == null) {
        // No user is signed in
    } else {
        // User logged in
    }
}

Using the second method you can get the complete FirebaseUser object in next activity if the user is signed in. Or, you can use Intent to pass data between activities.

Vedprakash Wagh
  • 3,595
  • 3
  • 12
  • 33
  • thanks for explaining, I understand that firebase is helping to connect so we can use it in both activity, also does it work if I logout with same code in the next activity with mGoogleSignInClient.signOut().addOnCompleteListener(this, task -> updateUI(null)); – Rohit Singh Rawat May 26 '19 at 13:21
  • Yeah. It'll work if user is signed in to the app already. It's one time thing, for example, if user logs in to the app using firebase, user stays logged in throughout the complete app unless you clear the data or sign out the user or if you block the user from your project. Please mark answer as accepted if it solved your issue, it'd help a lot. – Vedprakash Wagh Jun 05 '19 at 14:23