How to get all details about friend lists from facebook - android

I have this snippet
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
Bundle bundle = new Bundle();
bundle.putString("fields", "birthday");
mAsyncRunner.request("me/friends", bundle, new FriendListRequestListener());
and it works somehow, I mean I can read the ids from all my friends.
But in I want to read everything how can I do that ?
String _error = null;
JSONObject json = Util.parseJson(response);
final JSONArray friends = json.getJSONArray("data");
for (int i = 0; i < friends.length(); i++) {
Log.v("id:", "id= "+friends.get(i).toString());
}
What should I do to get info about my friends and to read that info
I guess this is the key, this is from the example I found and it works fine
bundle.putString("fields", "birthday");
but when I put for example, doesn't works
bundle.putString("fields", "friends_relationships");
-----------------EDIT 1-------------------------
code for permissions
mFacebook.authorize(Example.this, new String[] {"offline_access", "user_interests", "friends_interests","friends_relationships","friends_relationship_details"},new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
-------------- EDIT 2 --------------
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}

Graph API is the smart choice in most cases. To retrieve your friend information you need to collect some extended permissions from the user first. Then you can retrieve a lot more information other than the basic ones.
Following is a list of extended permissions related to friends different kind of information
friends_about_me
friends_activities
friends_birthday
friends_checkins
friends_education_history
friends_events
friends_games_activity
friends_groups
friends_hometown
friends_interests
friends_likes
friends_location
friends_notes
friends_online_presence
friends_photo_video_tags
friends_photos
friends_relationship_details
friends_relationships
friends_religion_politics
friends_status
friends_subscriptions
friends_videos
friends_website
friends_work_history
facebook.authorize(this, new String[] {"offline_access", "user_interests", "friends_interests"},
Edit :-
If your app needs more than this basic information to function, you
must request specific permissions from the user. This is accomplished
by passing String[] of permissions to the authorize method. The
following example shows how to ask for access to user's email address,
get extended access token and check-in user at a place:
facebook.authorize(this, new String[] { "email", "publish_checkins" },
new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
}
);
Look at here for more details.
Edit :-
mAsyncRunner.request("me/friends?fields=id,name,birthday,relationship_status", new FriendListRequestListener());
JSONObject json = Util.parseJson(response);
final JSONArray friends = json.getJSONArray("data");
for(int i=0;i<friends.length();i++)
{
JSONObject object = friends.getJSONObject(i);
Log.i("------------------ Id",object.getString("id"));
Log.i("------------------ Name",object.getString("name"));
Log.i("------------------ RelationShip",object.getString("relationship_status"));
}

There are separate permissions for your friends relationships. Check out the permissions documentation.
You'll want to request -
friends_relationships
friends_relationship_details

This is now longer possible as of May 2015 when the v1.0 facebook Graph API got deprecated.

try this :
Bundle params = new Bundle();
params.putString("fields", "name, picture, location");
mAsyncFacebook.request("me/friends",params, new RequestListener(){
#Override
public void onComplete(String response, Object object) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
} catch (JSONException e) {
Log.d(TAG,"Exception :"+e);
}
}
}
to know about the keys see this link : https://developers.facebook.com/docs/authentication/permissions/

Related

Cannot get the facebook's user's timeline with api 2.5

I'm trying to get the facebook's user's timeline in my Android app.
Here my code :
mLoginButton.setReadPermissions(Arrays.asList("user_about_me", "user_friends", "user_likes",
"user_photos", "user_relationships", "user_posts",
"user_status"));
// If using in a fragment
mLoginButton.setFragment(this);
// Other app specific specialization
// Callback registration
mLoginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
mAccessToken = loginResult.getAccessToken();
for (String permission : loginResult.getRecentlyGrantedPermissions()) {
Log.d(LOG_TAG, "Granted Permission:" + permission);
}
getUserFeed();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
And after the login, I launch this :
private void getUserFeed() {
Bundle params = new Bundle();
params.putInt("limit", 25);
params.putString("fields", "id,name,link,full_picture,message,story,picture,type,place,from,to");
params.putBoolean("summary", true);
/* make the API call */
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me/home",
params,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
try {
final JSONArray data = response.getJSONObject().getJSONArray("data");
//currentJson = response.getJSONObject();
} catch (JSONException e) {
Log.e("Error: ", e.toString());
}
}
}
).executeAsync();
}
I have this respond code from Facebook :
Requires extended permission: read_stream
I know this permission is depreceted, I'm using the latest API 2.5.
Do you know if we can continue to get the user's timeline now, if I replace the "/me/home" by "/me/feed" it's ok, but I just get my posts, not my entire timeline.
Thanks :)
Do you know if we can continue to get the user's timeline now,
No, you can’t.
if I replace the "/me/home" by "/me/feed" it's ok, but I just get my posts, not my entire timeline.
/me/home was deprecated together with the permission.
/me/feed is what you can get now, and that’s it.
Which posts you can expect to see is listed here: https://developers.facebook.com/docs/graph-api/reference/v2.5/user/feed#readperms

Post the comment on any wall of Facebook in Android

I am using Facebook sdk, (https://github.com/facebook/facebook-android-sdk/) to show the NewsFeed. I can be show the all newsfeed wall in my application.
Now I need to send the comment on the any wall which is visible by me. And how I can be like the wall and the comment through my application. Can anybody plz help me in this?
Thanks in advance.
To be clear:
you can only comment on posts (not the actual wall itself)
you can only like a comment or post (not the actual wall itself)
Using the Facebook SDK you can do the following for comments:
Facebook facebook = new Facebook(APP_ID);
String commentText = "I love blu-ray";
String postId = "7568536355_333422146668093"; //a lifehacker post about blu-ray
String graphPath = postId + "/comments";
Bundle params = new Bundle();
params.putString("message", commentText);
facebook.request(graphPath, params, "POST");
... and the following for likes:
Facebook facebook = new Facebook(APP_ID);
String postId = "7568536355_333422146668093"; //a lifehacker post about blu-ray
String graphPath = postId + "/likes";
facebook.request(graphPath, new Bundle(), "POST");
You can parse all feeds using graph api by passing
mAsyncRunner.request("me/home", params, new graphApiRequestListener());
it returns you json data with all your post and comments and likes
you can parse that data get all commnets
for further information search for hackbook for android example
You should get familiar with Facebook Android SDK usage of Graph API, Post object (comments connection) and Comment Object Graph API documentation (likes section).
You can't comment on the wall itself but on one of the posts.
You can post on the wall via Graph API
You can comment on post via Graph API
You can create likes for both Posts and Comments via Graph API
Update:
Example below about creating comment and liking it (samples of how to create comment for post and like the post already shown in other answer to this question):
// I assume you already have post_id (which is constructed from USERID_MESSAGEID)
Facebook mFacebook = new Facebook(APP_ID);
Bundle params = new Bundle();
params.putString("message", "This is a comment text");
String comment_id = facebook.request(post_id + "/comments", params, "POST");
// Once you have comment_id it can be used for liking it.
facebook.request(comment_id + "/likes", new Bundle(), "POST");
'Use Facebook Api as library download api and use it as library'
private static final String FACEBOOK_APPID = "Your Api key";
Facebook facebook = new Facebook(FACEBOOK_APPID);
facebook.authorize(this,new String[] { "user_photos,publish_checkins,publish_actions,publish_stream" },
new DialogListener() {
#Override
public void onComplete(Bundle values) {
postImageonWall();
try {
facebook.logout(TestActivity.this);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// finish();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
use postImageOnWall method
public void postImageonWall() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile(filepath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new RequestListener() {
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
Log.d("MalformedURLException", e.getMessage());
}
#Override
public void onIOException(IOException e, Object state) {
Log.d("onIOException", e.getMessage());
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
Log.d("FileNotFoundException", e.getMessage());
}
#Override
public void onFacebookError(FacebookError e, Object state) {
Log.d("onFacebookError", e.getMessage());
}
#Override
public void onComplete(String response, Object state) {
Log.d("onComplete", response);
}
}, null);
}

Trouble with accessing friends using Facebook-Android SDK

I have been struggling with android and the Facebook's graph API and I'm sure this is a piece of cake for intermediate programmers. What I want is a very simple Android application that logs in a user to Facebook, get the users consent to access information and finally to seamlessly query the graph API to get the users friends. I mention the work seamless because I have seen many sample applications that require the user to push a "get friends" button but I do not want that. I wish to extract the users friends without requiring him to push anything.
I have pasted the code below. I am able to to log-in and grant permission to my application. Next, I expect it to display my friends but it just directs me to a blank page. The problem might be that I am accessing the graph API in the wrong place because the Logcat does not contain the messages I print before and after the request. Could you please help me.
public class FacebookLogin extends Activity {
Facebook mFacebook = new Facebook("XXXXXXXXXXXX");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
View linearLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
linearLayout = findViewById(R.id.main_layout);
mFacebook.authorize(this, new DialogListener() {
#Override
public void onComplete(Bundle values)
{
Log.d("Facebook-Example-Friends Request", "Started API request");
mAsyncRunner.request("me/friends", new FriendsRequestListener());
Log.d("Facebook-Example-Friends Request", "Finished API request");
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public class FriendsRequestListener implements RequestListener
{
/**
* Called when the request to get friends has been completed.
* Retrieve, parse and display the JSON stream.
*/
public void onComplete(final String response)
{
Log.d("Facebook-Example-Friends Request", "FriendsListenerOnComplete");
try
{
JSONObject json = Util.parseJson(response);
final JSONArray friends = json.getJSONArray("data");
FacebookLogin.this.runOnUiThread(new Runnable()
{
public void run()
{
int l = (friends != null ? friends.length() : 0);
for (int i=0; i<l; i++)
{
try
{
JSONObject o = friends.getJSONObject(i);
TextView tv = new TextView(FacebookLogin.this);
tv.setText(o.getString("name"));
((LinearLayout) linearLayout).addView(tv);
}
catch(JSONException e)
{
Toast.makeText(getApplicationContext(), "JSON parsing error", Toast.LENGTH_LONG);
}
}
}
});
}
catch(JSONException e)
{
Log.d("Facebook-Example-Friends Request", "JSON Error in response");
}
catch(FacebookError e)
{
Log.d("Facebook-Example-Friends Request", "Facebook Error in response");
}
}
}
}
i think you see this answer you got some idea..
Facebook/Twitter Integration in my android application
and
http://android-sample-solution.blogspot.com

Android: get facebook friends list

I am using the Facebook SDK to post messages on walls.
Now I need to fetch the Facebook friends list. Can anybody help me with this?
-- Edit --
try {
Facebook mFacebook = new Facebook(Constants.FB_APP_ID);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
Bundle bundle = new Bundle();
bundle.putString("fields", "birthday");
mFacebook.request("me/friends", bundle);
} catch(Exception e){
Log.e(Constants.LOGTAG, " " + CLASSTAG + " Exception = "+e.getMessage());
}
When I execute my activity, I'm not seeing anything, but in LogCat there is a debug message like:
06-04 17:43:13.863: DEBUG/Facebook-Util(409): GET URL: https://graph.facebook.com/me/friends?format=json&fields=birthday
And when I tried to access this url directly from the browser, I'm getting the following error response:
{
error: {
type: "OAuthException"
message: "An active access token must be used to query information about the current user."
}
}
You are about half way there. You've sent the request, but you haven't defined anything to receive the response with your results. You can extend BaseRequestListener class and implement its onComplete method to do that. Something like this:
public class FriendListRequestListener extends BaseRequestListener {
public void onComplete(final String response) {
_error = null;
try {
JSONObject json = Util.parseJson(response);
final JSONArray friends = json.getJSONArray("data");
FacebookActivity.this.runOnUiThread(new Runnable() {
public void run() {
// Do stuff here with your friends array,
// which is an array of JSONObjects.
}
});
} catch (JSONException e) {
_error = "JSON Error in response";
} catch (FacebookError e) {
_error = "Facebook Error: " + e.getMessage();
}
if (_error != null)
{
FacebookActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Error occurred: " +
_error, Toast.LENGTH_LONG).show();
}
});
}
}
}
Then in your request you can specify the request listener to use for receiving the response from the request, like this:
mFacebook.request("me/friends", bundle, new FriendListRequestListener());
Using FQL Query
String fqlQuery = "SELECT uid, name, pic_square FROM user WHERE uid IN " +
"(SELECT uid2 FROM friend WHERE uid1 = me() LIMIT 25)";
Bundle params = new Bundle();
params.putString("q", fqlQuery);
Session session = Session.getActiveSession();
Request request = new Request(session,"/fql", params,HttpMethod.GET, new Request.Callback(){
public void onCompleted(Response response) {
Log.i(TAG, "Result: " + response.toString());
try{
GraphObject graphObject = response.getGraphObject();
JSONObject jsonObject = graphObject.getInnerJSONObject();
Log.d("data", jsonObject.toString(0));
JSONArray array = jsonObject.getJSONArray("data");
for(int i=0;i<array.length();i++)
{
JSONObject friend = array.getJSONObject(i);
Log.d("uid",friend.getString("uid"));
Log.d("name", friend.getString("name"));
Log.d("pic_square",friend.getString("pic_square"));
}
}catch(JSONException e){
e.printStackTrace();
}
}
});
Request.executeBatchAsync(request);
I was dealing with that and I found the answer.
The problem is that you want to access to your data without previous registration with your facebook token.
First, you must to define your Facebook variable:
Facebook mFacebook = new Facebook(getString(R.string.fb_id));
Later, define your AsyncFacebookRunner:
final AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
Ok, now you must to authorize your request, with autorize method. Note that you must implement callback methods on DialogListener(), put attention on onComplete() method. On that method you must to run the friend fetch request. Now your request will pass because now you are authenticated.
Now the code:
mFacebook.authorize(this, fb_perms, new DialogListener(){
/**
* Triggered on a successful Facebook registration.
*/
public void onComplete(Bundle values) {
mAsyncRunner.request("me/friends", new FriendListRequestListener());
}
/**
* Triggered on a FacebookError.
*/
public void onFacebookError(FacebookError e) {
}
/**
* Triggered on a DialogError.
*/
public void onError(DialogError e) {
}
/**
* Triggered when the User cancels the Facebook Login.
*/
public void onCancel() {
}
});
You can use the FriendListRequestListener class that was post by #Kon
I hope this helps.
Cheers!
Hi Please check below link
Facebook API for Android: how to get extended info regarding user`s friends?
Post on user's friends facebook wall through android application
I faced the same problem yesterday.
I wondering if you have overriden the onActivityResult() function?
private Facebook mFacebook=null;
...
...
...
#Override
protected void onActivityResult(int requestCode,
int resultCode,
Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
Check this answer in order to know how to get Facebook friend list and who of these friends have installed your app using new Facebook SDK 3.0 for Android.
I'm doing something like this is working good....
jsonObj = Util.parseJson(facebook.request("me/friends"));
JSONArray jArray = jsonObj.getJSONArray("data");
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.v("THIS IS DATA", i+" : "+jArray.getJSONObject(i));
}
Hope it is helpful...
If somebody is reading this in late 2015, the answer and code is quite simple. Take a look at official documentation here (in the code window click on Android SDK).
Keep in mind that you need to have user_friends permission.
Bro tip for android-rx users - get your friends synchronously, then process message and return Observable:
public Observable<List<Friend>> execute() {
return Observable.defer(new Func0<Observable<List<Friend>>>() {
#Override
public Observable<List<Friend>> call() {
AccessToken a = AccessToken.getCurrentAccessToken();
if (Utils.isValid(a)) {
try {
GraphResponse res = new GraphRequest(AccessToken.getCurrentAccessToken(), "me/friends").executeAndWait();
// process result
return Observable.just(your friend list);
} catch (Exception e) {
// notify user or load again
}
}
// invalid access token -> notify user
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}

Android: How to post update on Facebook wall automatically?

I want my android application to automatically post a preset message when the user click on a button. The preset message will be set by the user, so I am guessing that is not a violation of Facebook policies. How do I do this?
private static final String[] PERMISSIONS =
new String[] {"publish_stream", "read_stream", "offline_access"};
Facebook authenticatedFacebook = new Facebook(APP_ID);
postButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
authenticatedFacebook.authorize(Tests.this, PERMISSIONS,
new TestPostListener());
}
});
public class TestPostListener implements DialogListener {
public void onComplete(Bundle values) {
try {
Log.d("Tests", "Testing request for 'me'");
String response = authenticatedFacebook.request("me");
JSONObject obj = Util.parseJson(response);
Log.d("Tests", "Testing graph API wall post");
Bundle parameters = new Bundle();
parameters.putString("message", "Amit Siddhpura");
parameters.putString("description", "Hi Mr. Amit Siddhpura");
response = authenticatedFacebook.request("me/feed", parameters,
"POST");
Log.d("Tests", "got response: " + response);
} catch (Throwable e) {
e.printStackTrace();
}
}
public void onCancel() {
}
public void onError(DialogError e) {
e.printStackTrace();
}
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
}
You have to create Application on Facebook
And get authenticate from user, then you can get a access_token to post some message through Graph API
I think your application have to request extended permissions : publish_stream, offline_access
There is Facebook-Android-SDK source code on github, you can refer it.
http://developers.facebook.com/docs/guides/mobile
http://www.androidpeople.com/android-facebook-api-example-using-fbrocket/

Categories

Resources