In my app it is possible to login with Facebook and after the successful login I want to display a toast message which says "Welcome back, username (which is the displayName)". I managed to display a message but without the username since I don't know how to get it from Firebase and display it after the login.
Here is the code that handles the Facebook login:
private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
progressBar.setVisibility(View.VISIBLE);
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();
updateUI(user);
// Todo make a toast with the username
Toast.makeText(SignInActivity.this, "Welcome back", Toast.LENGTH_SHORT).show();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(SignInActivity.this, "Error.",
Toast.LENGTH_LONG).show();
updateUI(null);
}
progressBar.setVisibility(View.INVISIBLE);
}
});
}
Once you have the Facebook access token you can use GraphApi to get user's additional info:
val request = GraphRequest.newMeRequest(
accessToken
) { user, _ ->
try {
val name = user.getString("name")
Toast.makeText(context, "Hello, $name!", Toast.LENGTH_SHORT).show()
} catch (e: JSONException) {
Timber.d("Unable to get user name")
}
}
val parameters = Bundle()
parameters.putString("fields", "name")
request.parameters = parameters
request.executeAsync()
Here' code snippets in java
public void requestData(){
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object,GraphResponse response) {
JSONObject json = response.getJSONObject();
try {
if(json != null){
String name = user.getString("name");
Toast.makeText(context, "Welcome "+name, Toast.LENGTH_SHORT).show()
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,picture");
request.setParameters(parameters);
}