Facebook SDK for Android GraphUser - android

I am able to access the id, firstname, lastname, gender, and email of a GraphUser by using the following code.
But, I also need access to "location", "number of friends", "basic info" and "work company". How can this be done? I have tried other stackoverflow links, and checked the Facebook SDK link, but not getting a break through. Could I be provided code to directly access the required fields in the same way as the data that I already have?
What other permissions would I need?
loginBtn.setReadPermissions(Arrays.asList("public_profile", "email", "user_friends", "user_birthday", "read_friendlists"));
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
login_text.setText("Please login to continue");
userDetails = new JSONObject();
try {
Log.d("user birthday", user.getBirthday());
userDetails.put("fbId", user.getId());
userDetails.put("firstName", user.getFirstName());
userDetails.put("lastName", user.getLastName());
userDetails.put("gender", user.getProperty("gender").toString());
userDetails.put("email", user.getProperty("email").toString());
} catch (JSONException e) {
Log.d("Error: ", "Error setting user settings in FBActivity");
}
} else {
//login_text.setText("You are not logged");
}
}
});
EDIT:
I got everything except the total number of friends an individual has. How can that be done. I have gone through your links and it seems that I need to call another GraphRequest link. But I don't that. I want the total number of friends (no names, no details, just the number). I have added the permission "user_friends". What code should I write to get the number?

This is a pretty straightforward answer and the facebook documentation covers these details. https://developers.facebook.com/docs/reference/android/current .
https://developers.facebook.com/docs/graph-api
Here is the answer anyway!
You will need user_friends for the number of friends. It returns the total count of friends.
The default permission set called "basic info" has been removed, and replaced by "public profile".
user_location for location.
user_work_history for the work company.
please note : users can choose to not give these permissions to your app, in which case you should handle those scenarios properly, else your app will get rejected in the review process.

To get number of friends please refer to the following link:
https://developers.facebook.com/docs/graph-api/reference/v2.4/user/friends
Permissions needed would be: user_friends, which you already have included..
You'll get friends count in field 'summary' in the name of total_count
Similar question: facebook api on android - how can I get the number of friends that a user has?
loginBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
new GraphRequest(
loginResult.getAccessToken(),
"/me/friends",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.i("response", response.getJSONArray().toString()); //find the summary 'total_count' in the response
}
}
).executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});

Related

issue while opening user facebook page by user_link

I am getting this error message while trying to open the facebook page of the user.The strange thing is that if I have a mutual friend with that user the page loads with no problem, but I don't think it's default behavior, otherwise I can't understand the meaning of user_link permission.
Facebook has approved user_link permission and I passed App Review.
From developer account I changed the API version the app calls to v3.1.
The way I am getting user_link
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("user_gender", "user_link"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
makeGraphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
public void makeGraphRequest(AccessToken token) {
GraphRequest request = GraphRequest.newMeRequest(
token, (object, response) -> {
try {
userStorage.setUserProfileUrl(object.getString(AppConstants.LINK));
} catch (JSONException e) {
e.printStackTrace();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,gender,link,picture.width(700).height(700)");
request.setParameters(parameters);
request.executeAsync();
}
And using this answer for opening the page.
Intent intent;
try {
context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" + currentUser.getLink()));
context.startActivity(intent);
} catch (Exception e) {
intent = new Intent(context, FacebookWebViewActivity.class);
intent.putExtra(AppConstants.USER_LINK, currentUser.getLink());
context.startActivity(intent);
}
build.gradle
implementation 'com.facebook.android:facebook-login:4.33.0'
I will be very thankful if someone can suggest any solution. I faced this issue before the facebook new API version also.
From this post we can find the following bit of text
For most apps, links will only redirect to the individual's Facebook
profile for logged in people in the person's extended network.
So, I guess there is no way to be 100% sure that the user page will be loaded properly.
https://developers.facebook.com/docs/graph-api/changelog/version3.0#login
...the following fields that belonged to public_profile are deprecated...
As you can read in the changelog, the "link" and "gender" fields are deprecated.
Edit: But they have introduced new permissions user_link and user_gender so that users can explicitly asked for those particular fields. (Thanks to CBroe for pointing that out)

Content Not Found while opening user page on facebook [duplicate]

I am getting this error message while trying to open the facebook page of the user.The strange thing is that if I have a mutual friend with that user the page loads with no problem, but I don't think it's default behavior, otherwise I can't understand the meaning of user_link permission.
Facebook has approved user_link permission and I passed App Review.
From developer account I changed the API version the app calls to v3.1.
The way I am getting user_link
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("user_gender", "user_link"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
makeGraphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
public void makeGraphRequest(AccessToken token) {
GraphRequest request = GraphRequest.newMeRequest(
token, (object, response) -> {
try {
userStorage.setUserProfileUrl(object.getString(AppConstants.LINK));
} catch (JSONException e) {
e.printStackTrace();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,gender,link,picture.width(700).height(700)");
request.setParameters(parameters);
request.executeAsync();
}
And using this answer for opening the page.
Intent intent;
try {
context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" + currentUser.getLink()));
context.startActivity(intent);
} catch (Exception e) {
intent = new Intent(context, FacebookWebViewActivity.class);
intent.putExtra(AppConstants.USER_LINK, currentUser.getLink());
context.startActivity(intent);
}
build.gradle
implementation 'com.facebook.android:facebook-login:4.33.0'
I will be very thankful if someone can suggest any solution. I faced this issue before the facebook new API version also.
From this post we can find the following bit of text
For most apps, links will only redirect to the individual's Facebook
profile for logged in people in the person's extended network.
So, I guess there is no way to be 100% sure that the user page will be loaded properly.
https://developers.facebook.com/docs/graph-api/changelog/version3.0#login
...the following fields that belonged to public_profile are deprecated...
As you can read in the changelog, the "link" and "gender" fields are deprecated.
Edit: But they have introduced new permissions user_link and user_gender so that users can explicitly asked for those particular fields. (Thanks to CBroe for pointing that out)

android parse sdk facebook login cannot get email

Im integrated parse and facebook sdk to my project and its work and i get id and user name of facebook user
my issue is i cannot get any thing else like email or gender or any other information even i add the permission for them.
this is permission :
private static final List<String> Permissions = Arrays.asList("public_profile","email","user_friends","user_birthday","user_location","user_relationships");
button click code :
Button mBtnFb=(Button)findViewById(R.id.mBtnFb);
mBtnFb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseFacebookUtils.logInWithReadPermissionsInBackground(MainActivity.this,Permissions , new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("MyApp", "The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d("MyApp", "User signed up and logged in through Facebook!");
getUserDetailsFromFB();
} else {
Log.d("MyApp", "User logged in through Facebook!");
getUserDetailsFromParse();
}
}
});
}
});
get user details from facebook:
public String name,email;
ParseUser parseUser=new ParseUser();
private void getUserDetailsFromFB() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
String id=object.getString("id");
String name=object.getString("name");
String email=object.getString("email");
String gender=object.getString("gender");
String birthday=object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email");
request.setParameters(parameters);
request.executeAsync();
}
I get id and name only and any other info give me exception any suggestion ?
I had exactly the same issue, here's how I solved it:
Go to https://developers.facebook.com/
Click "Tools & Support" (at top menu)
Click "Graph API Explorer" (at left side menu called "Tools")
Where it says "Application: Graph API Explorer" (at the top right) change it to the application you are working with.
Where it says "Get Token" click "Get User Access Token"
Tick "user_about_me"
Click on "Extended Permissions"
Tick "email"
Click "Get Access Token"
Facebook may prompt you to confirm.
This should then give your application the permission to retrieve the email address of the facebook user.
Hope this helps.
Regards,
Nathanial

How to link Google + signed in users on Parse backend on Android?

I've been using Parse for 3 months in my android app. Now I want to add email login and social sign ons (Facebook and Google+) in the app. I have successfully added email and fb login and the user can connect both or either one of email or facebook and the app would recognise the user.
e.g. If I login through email, then connect facebook, use the app on another device, login via facebook, the app would know it's the same user and would be customised for me and would show my data. And email also works.
I have added Google+ sign-in for Android but I am not able to connect the user's Google+ credentials with the logged in user.
Parse Users table has an authData field which gets the facebook auth data and would get Twitter as well as both of these sign ons are baked into Parse SDKs.
What should be the best thing to do for Google+? I'm confused about the db design as well as how to connect the user who signed in with Google+?
What if the user just logs in via Google+? How do I make a Parse User and authenticate the user on Parse?
I'm comfortable with cloud code and Android and would really appreciate some sort of help/instructions just pushing me in the correct direction. I have never used OAuth2 and with Parse login for email and Social Sign ons, I don't think I should get into it. But let me know if I'm wrong.
Thanks!
Update: I have read a lot of questions on Parse Questions and have checked out the become method plenty of times (because I kept thinking I'm missing something after reading that). Check this question - I'm currently in the same situation.
I have:
1. Implemented Google+ sign in.
2. Got access token using GoogltAuthUtil.
Stuck with:
3. How to link currently signed in Parse user after the user signs in with Google+?
4. How to create a new Parse User if Google+ was the user's first (and only ) login choice?
This seems to be similar with
How to create a parse _User account from a Android Google token?
Following is my answer in that thread:
1. New User
The flow is as below:
User authorizes and a token is acquired
We create a new user with a random password
You can create a ParseUser using following code inside the newChooseAccountIntent() method that return email.
ParseUser user = new ParseUser();
user.setUsername(mEmail);
user.setPassword(randomPassword);
user.setEmail(mEmail);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
// Hooray! Let them use the app now.
} else {
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
}
}
});
2. Returning User
This is the where most of people stuck, as I researched over the Internet. The flow is as below:
User authorizes and the app gets a token
We pass this token to Cloud Code to validate. We need to check if this token is signed by Google and if it is meant for us (android-developers (2013)).
After you can verify that the token is valid, you can query for the user in Cloud Code using Parse.Cloud.useMasterKey() method and return the session key by using getSessionToken() method on the query result.
Use the session key to save login state on disk by calling becomeInBackground method
To validate the token, you can send Parse.Cloud.httprequest to this endpoint: https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=. This is instructed in Google Identity Documentation. You will receive data as below:
{
"iss": "https://accounts.google.com",
"sub": "110169484474386276334",
"azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"email": "billd1600#gmail.com",
"at_hash": "X_B3Z3Fi4udZ2mf75RWo3w",
"email_verified": "true",
"aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"iat": "1433978353",
"exp": "1433981953"
}
Things need to compare are "aud", "azp" and "email" which are translated as audience, authorized party and email.
To query for the current user on Cloud Code:
var query = new Parse.Query(Parse.User);
query.equalTo("email",mEmail);
query.first({
success: function(user) {
// Use user..getSessionToken() to get a session token
},
error: function(user, error) {
//
},
useMasterKey: true
});
Note: Make sure you have following scope so that the email will show up when you check on Cloud Code: https://www.googleapis.com/auth/plus.profile.emails.read
There's a question about this on Parse's questions. It's right here and I'm pretty sure it answers your questions.
https://parse.com/questions/google-plus
It links to the parse blog, that has some workarounds on this.
It says that you can add any login into ParseUser. You would be doing something like this:
Parse.User.become("session-token-here").then(function (user) {
// The current user is now set to user.
}, function (error) {
// The token could not be validated.
});
Another site where you should take a look:
https://parse.com/tutorials/adding-third-party-authentication-to-your-web-app
This last one is official and has an example code
void createNewGPlusUser(final String email, String name) {
final ParseUser user = new ParseUser();
user.setUsername(email);
user.setPassword("my pass");
user.put("any other variable in User class", "value");
user.setEmail(email);
user.put("name", name);
signInParseUser(user, email);
}
void signInParseUser(final ParseUser user, final String email) {
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
Log.d("TAG", "Created user");
// Hooray! Let them use the app now.
login(email);
} else {
Log.d("TAG", "Failed Creating user");
e.printStackTrace();
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
}
}
});
}
void login(final String email) {
ParseUser.logInInBackground(email, "my pass", new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// Hooray! The user is logged in.
Log.d("TAG", "Login successful");
} else {
// Signup failed. Look at the ParseException to see what happened.
}
}
});
}
To do so, I have used the following code
ParseUser.becomeInBackground(ParseUser.getCurrentUser().getSessionToken(), new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (parseUser != null) {
parseUser.setUsername(userEmail);
//firstName and lastName I am getting from Person class of google plus api
parseUser.put("FirstName", firstName);
parseUser.put("LastName", lastName);
parseUser.saveInBackground();
ParseUtils.verifyParseConfiguration(context);
ParseUtils.subscribeWithUsername(strEmail);
Intent successIntent = new Intent(context, OurServicesActivity.class);
startActivity(successIntent);
overridePendingTransition(R.animator.fade_in, R.animator.fade_out);
finish();
} else {
Log.e(TAG, e.getMessage());
Utilities.showToast(context, "Something occurred");
}
}
});
Let me know if it helps or if you have used something else.
Try this
ParseUser.becomeInBackground("session-token-here", new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// The current user is now set to user.
} else {
// The token could not be validated.
}
}
})

Facebook friend list in Facebook Android SDK 3.14

I am trying to get friend list using Facebook Android SDK 3.14 but getting no results. Some pointed out that friends who are using my app can only be retrieved but I want to retrieve my complete friend list. Can anyone please tell me how can i achieve that?
I am using the following code:
<code>
Request.executeMyFriendsRequestAsync(session, new Request.GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
// TODO Auto-generated method stub
Log.i("mustang", "response; " + response.toString());
Log.i("mustang", "UserListSize: " + users.size());
}
});
Thanks,
new Request(
session,
"/me/friends",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
/* handle the result */
}
}).executeAsync();
Permission: A user access token with "user_friends"
permission is required to view the current person's friends.

Categories

Resources