1

I'm trying to open a user's facebook profile page as shown here. In my app, user login after giving permission to my app and I get the usual details like FB ID, name, email, etc. But I'm unable to open the profile page in browser using FB ID. Is there any other way to show the profile page?

   
public class MainActivity extends AppCompatActivity {

    CallbackManager callbackManager;
    AccessTokenTracker accessTokenTracker;
    AccessToken accessToken;
    String fbid;

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

        FacebookSdk.sdkInitialize(getApplicationContext());

        facebookOncreateCalling();

        Button loginbtn = (Button) findViewById(R.id.loginbtn);
        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    LoginManager.getInstance().logOut();

                } catch (Exception e) {
                    e.printStackTrace();
                }

                LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile", "user_friends", "email", "user_birthday", "user_about_me"));
            }
        });

       
 // Here I want to open facebook profile page in browser
        Button openWeb = (Button)findViewById(R.id.openWeb);
        openWeb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
                //String facebookUrl = "http://www.facebook.com/"+fbid;

                String facebookUrl = "https://www.facebook.com/profile.php?id=" + fbid;

                facebookIntent.setData(Uri.parse(facebookUrl));
                startActivity(facebookIntent);*/

                try {

                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/androiddevs"));
                    startActivity(intent);

                } catch (Exception e) {

                    e.printStackTrace();

                }

            }

        });

    }

////////////////////////////// Facebook login starts //////////////////////////////////////
    private void facebookOncreateCalling() {

        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    getApplicationContext().getPackageName(),
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("Facebook_KeyHash:", "KeyHash:-> " + Base64.encodeToString(md.digest(), Base64.DEFAULT));


            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);

        callbackManager = CallbackManager.Factory.create();

        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        System.out.println("sammy_accessToken "+loginResult.getAccessToken().getToken());

                        callGraphApi(loginResult);
                    }

                    @Override
                    public void onCancel() {
                        Log.e("====Login Activity===","Cancel");
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        Log.e("====Login Activity===","Error"+exception);
                    }
                });


        accessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(
                    AccessToken oldAccessToken,
                    AccessToken currentAccessToken) {
                accessToken = currentAccessToken;
            }
        };
        accessToken = AccessToken.getCurrentAccessToken();
    }

    private void callGraphApi(final LoginResult loginResult) {
        GraphRequest request = GraphRequest.newMeRequest(
                loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        try {

                            System.out.println("SAM_output "+object);
                           String fbUserId = object.optString("id");
                           String firstName = object.optString("first_name");
                           String lastName = object.optString("last_name");
                           String eMail = object.optString("email");

                           System.out.println("SAM_ID:" + " " + fbUserId);
                           System.out.println("SAM_First_Name:" + " " + firstName);
                           System.out.println("SAM_Last_Name:" + " " + lastName);
                           System.out.println("SAM_Email:" + " " + eMail);

                            fbid = fbUserId;

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,first_name,last_name,link,birthday,gender,email");
        request.setParameters(parameters);
        request.executeAsync();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
////////////////////////////// Facebook login ends ////////////////////////////////////////
}
Somnath Pal
  • 1,570
  • 4
  • 23
  • 42
  • _"as I saw in some SO post that username permission is deprecated"_ - there never was such a permission ... The `username` _field_ has been removed from the user object with API v2.0. – CBroe Jun 01 '17 at 13:25
  • So if there is no way to get username, how to open profile of a user using FB ID? I'm editing my question for same@CBroe – Somnath Pal Jun 01 '17 at 13:33
  • Just request the `link` field from the user profile, that gives you a URL in the form `https://www.facebook.com/app_scoped_user_id/123456789/`, and that will redirect to the user’s actual profile address when called in a browser. – CBroe Jun 01 '17 at 13:46

1 Answers1

0

you will get name by following statements loginusername = response.getString("name");

    LoginManager.getInstance().registerCallback(callbackmanager, new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(final LoginResult loginResult) {

        GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
                JSONObject response = graphResponse.getJSONObject();
                Log.e(LoginActivity.class.getSimpleName(), "response data is" + response.toString());
                try {


                    if (response.has("email")) {
                        login_userid = response.getString("id");
                        **loginusername = response.getString("name");**
                        login_user_email = response.getString("email");

                        profileUpdate.put("Login", "Facebook Login success");

                        cleverTap.event.push("Facebook Login success", profileUpdate);
                        creatCustomeDomain.facebookUrl = "https://www.facebook.com/" + login_userid;
                        creatCustomeDomain.name = loginusername;
                        creatCustomeDomain.email = login_user_email;
                        creatCustomeDomain.gcmId = gcmid;
                        creatCustomeDomain.gender = response.getString("gender");
                        creatCustomeDomain.profileImage = "https://graph.facebook.com/" + login_userid + "/picture?type=large";
                        socialkey = "facebookUrl";
                        socialurl = "https://www.facebook.com/" + login_userid;


                        checkCustomerExistance(login_user_email);

                    } else {
                        new CustomAlertDialog(context, new CustomAlertDialog.OnDismisslistener() {
                            @Override
                            public void onDismiss() {
                                fblogout();
                            }
                        }).showAlertDialog("OOPS!!", "Something went Wrong");

                    }

                    //gotoShowQrActivity(creatCustomeDomain);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email,gender,birthday");
        request.setParameters(parameters);
        request.executeAsync();

    }

    @Override
    public void onCancel() {
        profileUpdate.put("Login", "Facebook Login on Cancel");

        cleverTap.event.push("Facebook Login on Cancel", profileUpdate);
        LoggerUtils.error(LoginActivity.class.getSimpleName(), "on cancel");

    }

    @Override
    public void onError(FacebookException e) {
        LoggerUtils.error(LoginActivity.class.getSimpleName(), "on error" + e);

        profileUpdate.put("Login", "Facebook Login Error");

        cleverTap.event.push("Facebook Login Error", profileUpdate);
    }
});
Punit Sharma
  • 2,951
  • 1
  • 20
  • 35
  • I don't need user's full name but its account username. Try opening this link in browser `https://touch.facebook.com/androiddevs`. You'll see Name and account username in left hand side. – Somnath Pal Jun 01 '17 at 12:57
  • I hope u will not get a username. because in their console they have not mentioned this thing.but try your luck – Vigneswara Sairam Andavarapu Jun 01 '17 at 13:36