attempting to get the number of friends from facebook api - android - android

I am attempting to the number of friends from facebook authentication api in an android application needed to call facebook permission api. Below is a snippet I am using
fbLoginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends"));
the app fails with a json exception at this line
PUBLICPROFILE = object.getString("public_profile"); //error here
EDITTED - Here is a snippet of my attempt:
Name = object.getString("name");
Email = object.getString("email");
DOB = object.getString("birthday");
DOB = object.getString("birthday");
PUBLICPROFILE = object.getString("/me/friends");
Log.v("Email = ", " " + Email);
Log.v("PUBLIC PROFILE = ", " " + PUBLICPROFILE);
Please does anyone know how I can the number of friends from facebook on android login authentication

As per the facebook developer api /{user-id}/friends
1.the User's friends who have installed the app
2.the User's total number of friends (including those who have not installed the app making the query)
After getting facebook token you can use this implementation
GraphRequest request = GraphRequest.newGraphPathRequest(
accessToken,
"/{user-id}/friends",
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
// Insert your code here
}
});
request.executeAsync();
https://developers.facebook.com/docs/graph-api/reference/user/friends/

Related

Facebook's Graph Request returning null

I have an Android app that allows users to login with Facebook with their Login button. I've set the permission as follow for the loginButton :
loginButton.setReadPermissions(
"public_profile","user_birthday","user_location");
The login works fine but what i want to do is basically get some additional info about their birthdate and actual location in order to create a new "User" object and write it into my database in this way :
Bundle parameters = new Bundle();
parameters.putString("fields", "id,first_name,last_name,gender, birthday,link,location");
final User newUser= new User();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.i("***LoginResponse :",response.toString());
try {
String userGender = response.getJSONObject().getString("gender");
String firstName = response.getJSONObject().getString("first_name");
String lastName = response.getJSONObject().getString("last_name");
String facebookProfileLink = response.getJSONObject().getString("link");
String userBirthdate = response.getJSONObject().getString("birthday");
String userCity = response.getJSONObject().getJSONObject("location").getString("name");
Profile profile = Profile.getCurrentProfile();
String id = profile.getId();
String link = profile.getLinkUri().toString();
Uri profilePicture = profile.getProfilePictureUri(200,200);
Log.i("Link",link);
newUser.setUserAge(userBirthdate);
Log.i("****Login" + "UserBirthday", userBirthdate);
newUser.setUserEmail("default#facebook.com");
newUser.setUserGender(genderFixer(userGender));
newUser.setUserCity(userCity);
Log.i("****Login" + "UserCity", userCity);
newUser.setFacebookProfile(facebookProfileLink);
newUser.setUserName(firstName);
newUser.setUserSurname(lastName);
newUser.setProfileImage(profilePicture.toString());
String userId = mAuth.getCurrentUser().getUid();
mDatabaseReference.child(userId).setValue(newUser);
if (Profile.getCurrentProfile()!=null)
{
Log.i("Login", "ProfilePic" + Profile.getCurrentProfile().getProfilePictureUri(200, 200));
}
Log.i("****Login"+ "FirstName", firstName);
Log.i("****Login" + "LastName", lastName);
Log.i("****Login" + "Gender", userGender);
}catch (JSONException e) {
e.printStackTrace();
}
}
}
);
request.setParameters(parameters);
request.executeAsync();
}
I can read all the data but not "birthday" and "location" -> "name".
NOTE : i'm perfectly aware that those fields can be empty and i know how to handle it but i'm testing with an account that actually has those fields on the Facebook profile. This is the response i'm getting :
I/***LoginResponseĀ :: {Response: responseCode: 200,
graphObject: {
"id":"116293545526048",
"first_name":"Davide",
"last_name":"Harlee",
"gender":"male",
"link":"https:\/\/www.facebook.com\/app_scoped_user_id\/116293545526048\/"}, error: null}
This only happens on 2 test account i made while logging with my "real" facebook account i get all the information i need without problems getting location and birthday just fine

FB Graph api not working in build apk

I am integrating FB Graph API in my project using following code :
private void integrateFacebook(){
fbLoginButton =(LoginButton)findViewById(R.id.fb_login_button);
callbackManager = CallbackManager.Factory.create();
mLoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile"));
fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("Facebook", "Facebook Login Successful!");
token = loginResult.getAccessToken().toString();
Log.d("Facebook", "User ID : " + loginResult.getAccessToken().getUserId());
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Insert your code here
try {
String name = "";
String id =object.getString("id");
String img_url ="https://graph.facebook.com/"+id+"/picture?type=large";
String email= "";
if(object.has("id")){
name = object.getString("name");
}
if(object.has("email")){
email=object.getString("email");
}
if(object.has("email")){
email=object.getString("email");
}
UserActivation.getsharedInstance(getApplicationContext()).setUserName(name);
UserActivation.getsharedInstance(getApplicationContext()).setUserName(email);
SharedPref.getSharedPref().setValue(getApplicationContext(),"img_url",img_url);
SharedPref.getSharedPref().setValue(getApplicationContext(),"user_email",email);
submitData(name,email,null,null,"1","facebook",img_url,id);
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG,e.toString());
}catch(Exception e){
Log.d(TAG,e.toString());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, photos, picture{url}, email");
// parameters.putString("access_token", token);
request.setParameters(parameters);
request.executeAsync();
}
Now It is working in debug mode but when i try to run through build.apk it gives following error in log :
Request without access token missing application ID or client token.
How to solve this.
In your debug mode you get somehow the Facebook app-related keys and after building the project, the build no longer reaches that. So you need to review your ini files, database connections and other stuff to know why are Facebook credentials missing after the build. Look at how are the credentials used and find out where they come from. When you know the answer to that, you should be able to solve the problem by making sure that the build app reaches the juices.
The android key hash that you generated and entered in your app in the facebook developer panel must have been generated using debug.keystore. SO to make it work for release build you have to generate a release key hash.
Checkout the "Setting a release key hash" section of this Official Documentation

get Mobile number in Android Facebook Integration

In Facebook integration we can get email adddress by
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
User fbUser = new User();
Log.v(TAG, user.getProperty("email") + "");
}
});
When some one logged-in with facebook by using MOBILE NUMBER instead of EMAIL id.then,how to get that mobile number instead of email id.?
Facebook has retracted these features of the API due to privacy concerns.
Source: Here

User info from VKontakte in Android

I am writing an application that needs to use the user data taken from the client social network VKontakte.
I did authorize VKontakte.
VKSdk.initialize(sdkListener, String.valueOf(idVK), VKAccessToken.tokenFromSharedPreferences(this, sTokenKey));
And got AccessToken.
As now I get the name and email user?
You can request email scope from user, then get email from access token:
String email = VKSdk.getAccessToken().email;
String userId = VKSdk.getAccessToken().userId;
//Get user info
VKApi.users().get().executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
VKApiUser user = ((VKList<VKApiUser>)response.parsedModel).get(0);
Log.d("User name", user.first_name + " " + user.last_name);
}
});
But remember, email is only available after first access request.
Old answer:
You can't get an email. This is not available. But you can get user name:
VKApi.users().get().executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
VKApiUser user = ((VKList<VKApiUser>)response.parsedModel).get(0);
Log.d("User name", user.first_name + " " + user.last_name);
}
});
For now, you can't get user email.
But you can get other simple info from user profile via class
java.lang.Object
com.vk.sdk.VKObject
com.vk.sdk.api.model.VKApiModel
Here is all available info:
http://vkcom.github.io/vk-android-sdk/com/vk/sdk/api/model/VKUser.html
After login user
I use this code
final VKRequest request = VKApi.users().get(VKParameters.from(VKApiConst.FIELDS, "photo_200, contacts"));
request.executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
VKApiUserFull user = ((VKList<VKApiUserFull>)response.parsedModel).get(0);
NavigationHelper.replaceFragment(getActivity().getSupportFragmentManager(), FrHome.newInstance(String.format("%s %s,", user.first_name, user.last_name), user.mobile_phone, user.photo_200), false);
}
});
List fields you can found here
https://vk.com/dev/users.get

How to track Facebook appRequest that send from Unity app?

I want to track invites that send from "player_1" to other players to count them and as result give "player_1" some reward. Like in PVZ2.
Ok, Facebook have SDK for Unity3d. Here is API to call App request dialog that allow to invite player:
public static void AppRequest(
string message,
string[] to = null,
string filters = "",
string[] excludeIds = null,
int? maxRecipients = null,
string data = "",
string title = "",
FacebookDelegate callback = null)
Facebook doc says something about redirect_url that could be used to track user's that accept indentations:
https://developers.facebook.com/docs/reference/dialogs/requests/
But Unity plugin doesn't have this param.
Also doc says that follow:
Requests are only available for games on Facebook.com or iOS and
Android apps. Accepting a request from a game will direct the person
to the Canvas Page URL of the app that sent the Request. For native
mobile apps, accepting the request will direct the person to the app
on their device if installed or to the appropriate location (Apple App
Store or Google Play) to download the app otherwise.
Game is going to work on mobile devices only. Therefore we don't need to make Facebook Canvas application. Should I implement this Canvas URL script on our website anyway?
Where is the correct place to inject code (server side script) to track Facebook app requests?
UPDATE:
Thanks to Bhavesh Vadalia for answer: https://stackoverflow.com/a/21597185/425707
I've decided to not handle friends requests in Canvas App.
Here is solution for Facebook SDK 5.0.3:
// Quesry string: "/fql?q=SELECT uid, name, is_app_user, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 1";
string q = "/fql?q=SELECT+uid,+name,+is_app_user,+pic_square+FROM+user+WHERE+uid+IN+(SELECT+uid2+FROM+friend+WHERE+uid1+=+me())+AND+is_app_user+=+1";
FB.API(q, Facebook.HttpMethod.GET, friendsResult =>
{
if (friendsResult.Error != null)
{
FbDebug.Error(friendsResult.Error);
}
else
{
FbDebug.Log(friendsResult.Text);
}
});
Here is implement for track code using facebook graph api implement in for my application. hope it also help to you.
I am using facebook 3.6 sdk
private void requestMyAppFacebookFriends(Session session) {
Request friendsRequest = createRequest(session);
friendsRequest.setCallback(new Request.Callback() {
#Override
public void onCompleted(Response response) {
List<GraphUser> friends = getResults(response);
Log.e("RESULT : ", "#"+friends.size());
for(int i =0;i<friends.size(); i++){
GraphUser user = friends.get(i);
boolean installed = false;
if(user.getProperty("installed") != null){
installed = (Boolean) user.getProperty("installed");
}
if(installed){
Log.e("USER NAME", "#"+friends.get(i).getId());
}
}
// TODO: your code here
}
});
friendsRequest.executeAsync();
}
private Request createRequest(Session session) {
Request request = Request.newGraphPathRequest(session, "me/friends", null);
Set<String> fields = new HashSet<String>();
String[] requiredFields = new String[] { "id", "name", "picture","installed" };
fields.addAll(Arrays.asList(requiredFields));
Bundle parameters = request.getParameters();
parameters.putString("fields", TextUtils.join(",", fields));
request.setParameters(parameters);
return request;
}

Categories

Resources