Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How do I get the full friend list of a person, using Android Studio and Facebook SDK 4.4.+. I have looked for tutorials everywhere but they are all out dated. I just need a simple code without installing any new libraries and I need some more explanation with the code
Straight from Facebook API Docs - https://developers.facebook.com/docs/graph-api/reference/v2.4/user/friends
This will only return any friends who have used (via Facebook Login) the app making the request.
If a friend of the person declines the user_friends permission, that friend will not show up in the friend list for this person.
This was something Facebook API did to us when they enforced v2 upon all apps.
Thanks Facebook.
Does that sound like you? Well you found the right question!
What you will need to perform the "Friend getting" is the Facebook Graph API. Facebook has a pretty good explanation on how to use their Graph API + you can test it with their Graph Explorer.
But may be you need more help? Well I can give it to you.
First integrate your Facebook SDK properly and add a log in button, so the person can Login.
From here on now comes the Graph API. I recommend you read the Graph API documentation and the list of permissions after you read this answer to understand this amazing tool even better.
Many say that after a certain update a while ago you cannot get a full friends list. Well they are partially correct. Facebook did change how some commands behave, but others are still at your dispolsal. For example the /taggable_friends
The taggable friends will give you an array of names that are all of your friends, who have not made their profile private. For example I have 409 friends, but this function shows them to me only up to the 406 person, because 3 have private accounts.
How to use the taggable_friends?
In the Log in code add this:
GraphRequest requestet =
new GraphRequest(
accessToken,
"/me/friends",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
JSONObject obj = response.getJSONObject();
JSONObject sum;
try {
sum = obj.getJSONObject("summary");
c=Integer.valueOf(sum.optString("total_count"));
fff.setText(sum.optString("total_count"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
);
GraphRequest requestt =
new GraphRequest(
accessToken,
"/me/taggable_friends",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
JSONObject obj = response.getJSONObject();
JSONArray arr;
try {
arr = obj.getJSONArray("data");
JSONObject oneByOne = arr.getJSONObject(1);
lmaYOLO.setText(Integer.toString(c)+" "+oneByOne.opt("name").toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
);
Bundle parameters = new Bundle();
parameters.putString("fields", "name");
requestet.executeAsync();
request.setParameters(parameters);
request.executeAsync();
requestt.setParameters(parameters);
requestt.executeAsync();
The first graph request that we use is the "requestet" what I do in there is get the number of friends of the logged in user, using the friends node.
In order to access any node you need to use JSONObject objname = previousobject.getJSONObject("name of node")
with objname, previousobject and name of node being changable according to your needs.
With taggable_friends it is more tricky, as you will get an Array of objects, each of which will contain a name of a friend. So you can see at the code how I get an Array same as the Object. Now at JSONObject oneByOne = arr.getJSONObject(1), the one is changable to any number of your friends list (REMEMBER arrays start from 0, so the first element will be getJSONObject(0)).
Now from here you can create a while loop, which will go from 0 to the number which we got from the /me/friends
You might have noticed that when I setText I use oneByOne.opt("name"). What opt does is GET the value of that node (in our case the name of the friend), unlike the getJSONObject, which opens the node.
Starting this program I will see on my screen appear:
406 - the number of non-private friends
Biggus Dickus - the second friend in my Facebook list (which is certainly not your Real life second friend).
Changin it to give me my first friend (remember you had to put 0),
I will get
407 (oh I accepted a new friend's request)
Martin Luther King
From here on you can do whatever you want with this code! Have Fund
You cannot get the whole friend list. Only those which are also using your app.
See:
https://developers.facebook.com/docs/apps/upgrading#upgrading_v2_0_user_ids
Related
I have tried using the code below and if add old facebook sdk it workd fine but new sdk I get only the friend who is on app.How can I get the list of all friends in new sdk? .I really appreciate any help .Thanks in Advance.:
new Request(
MainActivity.facebook.getSession(),
"/me/friends",
null,
HttpMethod.GET,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
/* handle the result */
Toast.makeText(activity, response.toString(), 5).show();
}
}
).executeAsync();
Short Answer: You Can´t.
Since v2.0, you can only get the friends who authorized your App too, for privacy reasons. An App should not know about anyone who does not use the App.
If you want the names to tag them, there is taggable_friends. If you want to invite them, use invitable_friends. But check out the docs for their limitations.
I am getting a wrong Facebook Friend Id: I am getting some long alphanumeric value in id which, among the other things, is also not unique (e.g. it changes on each call).
Actually I want to use this id as a unique identifier to login, but since it changes every time is not so helpful.
So what's wrong here? What else can I do for unique identification? Any suggestion will be appreciated.
I am using this code to get friend list:
Bundle required = new Bundle();
required.putString("fields", "uid, name, picture.type(square), gender, email");
//Request for friendlist from facebook
Request req = new Request(session, "me/taggable_friends", required, HttpMethod.GET,
new Callback() {
#Override
public void onCompleted(Response response)
{
is2=response.getGraphObject();
JSONObject json = is2.getInnerJSONObject();
readResponse(json);
String str = json.toString();
saveFileOnSD("data", str);
// generateNoteOnSD("frinedresponse", str);
Log.v(TAG, str);
}
});
Request.executeBatchAsync(req);
The problem is that you are using taggable_friends. Taggable_friends are for if you want to tag friends. It is by design that the id changes every single time you call it.
If you want friends you should use /me/friends but it will only return friends that are already using the app.
Depending on what you need all friends for some solutions can be found here: https://developers.facebook.com/docs/apps/faq
On 30th April 2014 facebook make so many changes, so if you create you facebook APP ID after this date you can't get facebook id of your friend with taggable_friend, so for getting facebook id of your friend you need to use "me/friends instead of me/taggable_friend", but you get only those friend list who are using your app.
I am having trouble while trying to post a message on the current end-user Facebook wall with my Android Application.
So far :
The user is logged in with all the required permissions, especially
the publish_actions permission ;
I am using the last version of Facebook SDK 3.x & Graph API v2 as of May 2014
Post to wall works now as of EDIT 2, but there are issues with
privacy settings : post cannot be seen by anyone not even the
recipient who is tagged in the post ! See EDIT 2 for more details
Here is the documentation for posting a message on the user wall :
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/feed (go to Publishing)
Regarding the message that needs to be posted on the user' wall, I need to tag some friends that were previously selected by the user.
But to use the tag field I need to use the place field.
The documentation says :
Name: tags
Comma-separated list of user IDs of people tagged in this post. You cannot specify this field without also specifying a place.
Type: csv[string]
Name: place
Page ID of a location associated with this post.
Type: string
What is location page ID ? How do I get it ?
Oddly enough, in my specefic case, I am offering the possibilty to the user to share is upcoming travel on Facebook.
More oddly enough, this travel is defined by dates and a destination (name of destination + latitude & longitude). The user has the possibility to also share this travel to his friends that are located in his travel's destination hence the need to tag his friends to the wall post.
[EDIT 1]
After looking into #Tobi solutions, I managed to post a message on the end-user wall (in my case me, since I am the developper).
So far : the message is correctly displayed with a friend tagged (a dummy account I use for tests purpouses) and there is also the place : Paris, France.
Using the following search query (thanks #Tobi) search?q=Paris,France&type=place I can get the ID of Paris, France.
Since I did not code the part to retrieve the Place ID it put it manually in the code for the sake of testing the feature first.
[END OF EDIT 1]
[EDIT 2]
I noticed I forgot to add the part with the privacy values to my args Bundle. But it did not change a damn thing : my post is only visible to me alone.
Going to my Facebook wall, here is what I get :
Hovering the public parameters of the posts (a padlock icon) says "All tagged persons".
Clicking on the icon shows the list of settings with only "Only me" selected.
Why "only me" even though I specifically said me + my dummy account in the request parameters ?
Even weirder : changing the property of the publication parameters to "customized" with my dummy account does not change a damn thing as well. Just why ? Facebook is really getting on my nerve...
For the rest, the message content is correctly displayed and the related place is the good one. At least a got that correctly. But still, I just don't get the rest ...
[END OF EDIT 2]
So here is the updated code :
if (this.session != null && this.session.isOpened()) {
final Bundle args = new Bundle();
if (this.selectedContacts.isEmpty() == false) {
args.putString("message", message);
args.putString("place", "170558129707208"); //manually added Paris, France ID
String tags = "";
//here I made some modifications regarding the tags so that is built correctly
for (int it = 0; it < this.selectedContacts.size(); it++) {
final String name = this.selectedContacts.get(it).toString();
final String friendID = String.valueOf(getIdFromName(name)); // returns an int
if (it == this.selectedContacts.size())
tags += friendID;
else
tags += friendID + ",";
}
// Forgot to add privacy values to bundle !
final JSONObject privacyValues = new JSONObject(); //not android JSON, but JSON-Simple lib
privacyValues.put("value", "CUSTOM");
String allow = this.currentUser.getId() + "," + tags;
privacyValues.put("allow", allow); // to limit the visibility of this post
args.putString("privacy", privacyValues.toJSONString()); //forgot that one...
final Request shareTravelRequest = new Request(this.session, this.currentUser.getID() + "/feed",
args, HttpMethod.POST, new Request.Callback() {
public final void onCompleted(final Response response) {
//TODO
}
}
);
final Response response = shareTravelRequest.executeAndWait();
if (response.getError() == null) // in this case, no error occurred
return true;
else {
this.lastErrorMessage = response.getError().getErrorMessage();
Log.e("Something went wrong while posting Facebook message", this.lastErrorMessage);
Log.e("Error type is", response.getError().getErrorType());
Log.e("Error code is", String.valueOf(response.getError().getErrorCode()));
return false;
}
}
}
Unfortunately I must have mistaken somewhere because although the post does appear on my Facebook wall with my dummy account tagged and with the correct link to the place, my dummy account cannot see the post.
I tried creating manually the same post on my Facebook wall by using the following settings :
First I supplied a message
Second I supplied a place
Third I tagged my dummy account
Four I choose who can see this post : me and my dummy account
And finally, I post the message.
In this case, my dummy account sees the post both on its wall and on my wall.
So I would like to know what parameters I must get wrong because there is not much parameters and I just don't see why.
Thanks !
You can either use the Search and use the type place (https://developers.facebook.com/docs/graph-api/using-graph-api/v2.0#search), or, if you have positioning date, use an FQL query on the place table (https://developers.facebook.com/docs/reference/fql/place/) as described here: Facebook places: order results by distance
Use two test accounts made via Facebook Developer App settings and not a dummy account that breaks TOS. Since you request publish_actions you probably didn't submit the app for review. Unless your dummy account is a developer/tester in roles as well (which is breaking the TOS again) then your dummy account will not be able to see the post.
Only developers and testers of an unpublished application can see posts made by that application.
I have a method in my app that allows the user to "like" a post in his/her news feed. It's done with a simple graph request using HttpMethod.POST. But when I try to do an "unlike" action using HttpMethod.DELETE, I get an error callback:
02-08 00:35:57.298: I/Detail(2628): {Response: responseCode: 403, graphObject: null, error:
{HttpStatus: 403, errorCode: 200, errorType: OAuthException, errorMessage: (#200)
Feed story publishing to other users is disabled for this application}, isFromCache:false}
Now I assume this has something to do with the latest attempt to make all apps that integrate with Facebook use all Facebook looking dialogs and styles, but I could be wrong. Here's the roadmap post that has me suspicious:
Removing ability to post to friends walls via Graph API We will
remove the ability to post to a user's friends' walls via the Graph
API. Specifically, posts against [user_id]/feed where [user_id] is
different from the session user, or stream.publish calls where the
target_id user is different from the session user, will fail. If you
want to allow people to post to their friends' timelines, invoke the
feed dialog. Stories that include friends via user mentions tagging or
action tagging will show up on the friend’s timeline (assuming the
friend approves the tag). For more info, see this blog post.
Any ideas on what I could be doing wrong, or is Facebook just ruining me? Thanks!
EDIT: Here's the code I'm using to run the request.
Request likeRequest = new Request(Utility.fbSession, null, null, null, new Request.Callback() {
#Override
public void onCompleted(Response response) {
String responseString = response.toString();
Log.i("Detail", responseString);
updateDetail();
}
});
HttpMethod nextLikeCall = HttpMethod.DELETE;
likeRequest.setHttpMethod(nextLikeCall);
likeRequest.setGraphPath(itemId+"/likes");
likeRequest.executeAsync();
When you grab the post id from the graph data, it should be in a format like: XXXXX_YYYYY. The XXXXX is simply the users id and YYYYY is the actual post id. What you need to do is extract and use just the YYYYY portion of the post id that graph gives you. so instead of graph.facebook.com/XXXXX_YYYYY/likes.... you want to send graph.facebook.com/YYYYY/likes. This will work with both liking and unliking, you can test in graph explorer first before hacking together a substring extraction method.
Not sure how to extract a section of a string on Android, but I know in Objective-C/iOS, it can be done like this (code not tested, for reference/idea) :
SString *actualPostIdStr; //The String we will put the actual postId in
NSString *oldIdStr = //<the string in format XXXXX_YYYYY>
NSInteger charCount = [oldIdStr length]; //get the length of the original XXXXX_YYYYY string
NSRange fRangeCount = [oldIdStr rangeOfString:#"_"]; //get count of characters to remove (XXXXXX)
if (fRangeCount.location != NSNotFound){
NSInteger startingPos = fRangeCount.location + 1; //get the starting character position of the actual postId
actualPostIdStr = [[oldIdStr substringWithRange:NSMakeRange(startingPos, charCount - startingPos)] copy];
}
Hope this helps.
EDIT:
Ok, so I have been playing around with likes all day... It seems that this method sometimes doesn't work, but it all depends on the type of graph object which you are attempting to like/unlike. For example... plain status posts, this method works perfectly. However, I ran into a problem when trying to like a photo with a message/story post object. It turns out, in the graph data for this type of post object with photo, there is an additional paramter called "object_id", in addition to the plain "id" that is in status post graph data. in this case, with the photo and story post, you need to pass the "object_id", unaltered for successful unliking.
This mess seems like either a bug on FB's end, or they are making changes and disallowing likes/unlikes from graph api & just forgot/haven't to told us yet :) hopefully the former. In the mean time, you're just going to have to use my above answer, but just make sure you test with as many different types of post objects you can find, and use if conditions when a different id (portion of "id"... "object_id"... etc) is required.
Sometimes Daniel McCarthy's method don't work. In this case we need get Graph API request XXX_YYYY, find field object_id and unlike this object_id fid.
I'm trying to discover if a user likes a specific facebook page by using Graph API inside an android application using the FB SDK v3.
The following call works and reports all of the likes of the user along with every other detail to do with each resulting item.
Request.executeGraphPathRequestAsync(session, "me/likes", new Request.Callback()
Since I'm not interested in any peripheral data, I just want to get the id back so I can lookup the page I'm interested in, but when I add the parameters as follows...
Request.executeGraphPathRequestAsync(session, "me/likes?fields=id", new Request.Callback()
... no object is returned from the call. If I post the same queries in the Graph API explorer they give back the expected results.
In addition to this question, is it at all possible to limit the result of the query to just the page ID to begin with, since I already know that piece of information? I have no use for the rest of the data being returned and would prefer not to chew up user bandwidth unnecessarily. I've searched high and low and it doesn't seem possible. Even the FQL explorer doesn't work when trying to limit by both user and page iD as the example suggests. I get an empty result set when adding 'AND page_id=xxx' to the query.
As far as i know, you cant run queries with field in 'executeGraphPathRequestAsync'.
instead use 'Request' and run in with 'RequestAsyncTask'.
Short example:
String grapPath = "me/home";
Bundle params = new Bundle();
params.putString("fields", "type,id,object_id,created_time,from,picture,likes");
params.putString("limit", "500");
Request request = new Request(session, grapPath, params, HttpMethod.GET, new Callback()
{
#Override
public void onCompleted(Response response)
{
if (response != null)
{
Log.d(TAG_NAME, "response: " + response.toString());
}
}
});
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
Hope i managed to help you :)
The Facebook SDK will add the "?access_token" to the end of the graph path string. So the graph command ends up looking like:
me/likes?fields=id?access_token
Break out the fields into a params Bundle.
Found this issue resolved in a Facebook bug post:
http://developers.facebook.com/bugs/314504765319932?browse=search_5116b87d245900257505334