Response code 200 from facebook - android

I'm developing new android app which uses facebook sdk. I want to fetch users friends list, I'm doing it like that:
Request request = Request.newMyFriendsRequest(
Session.getActiveSession(),
new Request.GraphUserListCallback() {
public void onCompleted(List<GraphUser> paramAnonymousList,
Response paramAnonymousResponse) {
Toast.makeText(getApplicationContext(),
paramAnonymousList.toString(),
Toast.LENGTH_SHORT).show();
Log.e(TAG, paramAnonymousList.toString()
+ paramAnonymousResponse.toString());
}
});
request.executeAsync();
However when I run app I'm getting something like that:
GraphObjectList{itemType=GraphUser, state=[]}{Response: responseCode: 200, graphObject: GraphObject{graphObjectClass=GraphObject, state={"data":[]}}, error: null, isFromCache:false}
I tried to run this code inside app which is not in development mode and it's working fine - i'm able to fetch user's data. What can be the cause of response code 200. According to that: https://developers.facebook.com/docs/graph-api/using-graph-api/v2.0 response code 200 belong to facebook permission errors. But to fetch user's friends list I don't have to provide any specific permissions, so what can be the cause of this response?
Thanks in advance

HTTP 200 means that your request is OK.
The real issue is Facebook API v2.0. Apps cannot retrieve the full list of friends for a user, only friends already using the application. Even if you application is still in v1.0, users who first logged in after May 1st are getting v2.0 behaviour.
Reference: https://developers.facebook.com/docs/graph-api/reference/v2.0/user/friends
Cheers!

I have done in this way and works fine perfectly in Facebook SDK 4.18.0
public class SignIn extends AppCompatActivity {
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//before set conteview
FacebookSdk.sdkInitialize(getApplicationContext());
// AppEventsLogger.activateApp(this);
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_signin);
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest graphRequest=GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
Log.d("Graph Response",graphResponse.toString());
String myCustomizedResponse = graphResponse.getJSONObject().toString();
Log.d("Ketan_Ramani",graphResponse.getJSONObject().toString());
try {
JSONObject obj = new JSONObject(myCustomizedResponse);
String id = obj.getString("id");
String first_name = obj.getString("first_name");
String last_name = obj.getString("last_name");
String email = obj.getString("email");
Log.d("Id",id);
Log.d("FirstName",first_name);
Log.d("LastName",last_name);
Log.d("Email",email);
} catch (JSONException e) {
Utils.hide_dialog();
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,first_name,last_name,email");
graphRequest.setParameters(parameters);
graphRequest.executeAsync();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}

Related

Facebook Profile getName() on Android always returning null

My Facebook Login Activity if it helps:
public class LoginActivity extends AppCompatActivity {
private LoginButton loginButton;
private CallbackManager callbackManager;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_login);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile", "user_friends");
final Intent myIntent = new Intent(this, MapsActivity.class);
if (isLoggedIn()) {
startActivity(myIntent);
finish();
return;
}
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(final View v) {
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile", "user_friends"));
startActivity(myIntent);
finish();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});
}
});
}
private boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
}
and the code I'm using to attempt to get someone's first name from their ID:
new Profile(creatorId, null, null, null, null, null).getFirstName()
I have tried the getFirstName() call shown here in addition to getName() and both always return null. I thought having "public_profile" in my requested Facebook permissions would allow me to get someone's name in this way if they have authorized my app while logging in through Facebook. However, I did not always have "public_profile" in my requested Facebook permissions, but I have forced all users to re-login through Facebook to my app with this current code and permissions, so I thought this would fix this problem. Nevertheless, this function keeps returning null and I'm not sure why.
Also, creatorId may be the FB ID of a different user than the currently logged in FB user. (They will have authorized+used the app in the past, just not the currently logged in user on that Android device).
So, it seems that a Graph Request is necessary, even for public profile information. Here is the Graph Request I used to get the first name for a certain Facebook ID, creatorId:
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
creatorId,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
try {
Log.e("creatorId's first name:", response.getJSONObject().getString("first_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle params = new Bundle();
params.putString("fields", "id,first_name");
request.setParameters(params);
request.executeAsync();
You can use this code.
please change your GraphRequest.GraphJSONObjectCallback() interface
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
try {
Log.e(TAG,"id"+user.optString("id"));
Log.e(TAG,"id"+user.optString("first_name"));
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,first_name");
request.setParameters(parameters);
request.executeAsync();`

Send a request with Facebook Data to Server in Android

I am new in Android Development, so please, don't consider my question a dumb one.
In my application I have authorization with email, Facebook and twitter. Email part is done, and now I am doing the Facebook authorization part using LoginManager. I reached to a point, where tapping on facebook icon, facebook authorization screen appears, user inserts his credentials, Facebook asks about permission to use the data of user. after it the screen closes and user returns to application Login screen. For email login, user's email and password are sent to server. in Facebook case I don't clearly understand what I should send and how should I do that. Here is my code, please someone help or hint - what I have not done correct ?
facebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call private method
onFacebookLogin();
}
});
****
private void onFacebookLogin()
{
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile", "user_birthday"));
LoginManager.getInstance().registerCallback(callbackmanager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("Success");
Bundle parameters = new Bundle();
parameters.putString("fields", "id, email, first_name, last_name, gender, user_birthday");
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json, GraphResponse response) {
if (response.getError() != null) {
// handle error
System.out.println("ERROR");
} else {
System.out.println("Success");
try {
String jsonresult = String.valueOf(json);
System.out.println("JSON Result" + jsonresult);
String email = json.getString("email");
String id = json.getString("id");
String firstname = json.getString("first_name");
String lastname = json.getString("last_name");
String gender = json.getString("gender");
String birthdate = json.getString("user_birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
request.executeAsync();
}
#Override
public void onCancel() {
Log.d("TAG_CANCEL", "On cancel");
}
#Override
public void onError(FacebookException error) {
Log.d("TAG_ERROR", error.toString());
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackmanager.onActivityResult(requestCode, resultCode, data);
ok I got the question. when your facebook login is success. fetch all information you need for sign In. like fetch the email address. and for password you can set a parameter authByFacebook="true". hope this works for you.
try to put the intent for moving to the next page after facebook login success
like below given code
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
//Toast.makeText(LoginActivity.this, "on success", Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("login_type", "facebook");
startActivity(intent);
finish();
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this, getResources().getString(R.string.facebook_app_id));
}
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this, getResources().getString(R.string.facebook_app_id));
}

How to have Access Token Facebook SDK 4.4.1

I want to use Facebook SDK to get my photo's url, and display it. I log in with fb sdk, but each time I open my app, I must log out and log in again to have access token. Can I have acces token without log in fb? And can I have access token of my friend's page? Please help me.
This is my code:
public class MainActivity extends Activity {
private CallbackManager callbackManager;
private ImageView image;
private LoginButton loginButton;
private AccessToken accessToken;
JSONObject jsObject = null;
public MyAsyncTask myAsy;
public String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.image);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("user_photos"));
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
accessToken = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
// Get images's url code
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "photos{images}");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// info.setText("Login attempt cancelled.");
}
#Override
public void onError(FacebookException e) {
// info.setText("Login attempt failed.");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
1) No, you can't get a user access token without first logging the user in. Access tokens have an expiry time and have to be renewed/re-issued from time to time.
2) If by "can I get an access token for a friend's page" mean if you can get an access token for a friend without said friend doing anything, then no, you can't. You need to have that friend login to your app just like every other user.

Login to facebook in android app and pull down friends listing. How do i get accessToken?

Having trouble not knowing where to get my AccessToken after logging into facebook from my android app. The code below is what I use to log in and it seems to work. But when I want to get a listing of friends, I don't know where to find the access token.
This is my subset of the code that logs in (from Facebook's developer site).
public class MainActivity extends ActionBarActivity {
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends");
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "Success!");
}
#Override
public void onCancel() {
Log.d(TAG, "Canceled");
}
#Override
public void onError(FacebookException exception) {
Log.d(TAG, String.format("Error: %s", exception.toString()));
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
This is the part I want to use to get my list.
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link");
request.setParameters(parameters);
request.executeAsync();
How do I set the variable accessToken?
Are there any good examples of simple ways to do this out there? Everything I find seems very complicated for my level and not using a newer sdk (4.1.2 is what I have) but something old that seems to be depricated.
There are some changes in Facebook SDK v.4 such as:
Session Removed - AccessToken, LoginManager and CallbackManager
classes supercede and replace functionality in the Session class.
Access Tokens - Briefly, you can load AccessToken.getCurrentAccessToken with
the SDK from cache or if the app is cold launched from an app
bookmark. For instructions, see Facebook Login for Android, Get
Current Token.
But you also need to write some code as described in the link.
After Login use this code to get Friend List of those friend who are using this app.
Now Facebook does not provide the whole list of friend.
GraphRequest.newMyFriendsRequest(AccessToken.getCurrentAccessToken(), new GraphJSONArrayCallback() {
#Override
public void onCompleted(JSONArray objects, GraphResponse response) {
// TODO Auto-generated method stub
try
{
Log.d("Garph Friend ", objects.toString(2));
friendCallback(objects.toString(2));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAndWait();

Android Facebook SDK 4.0 Login without Facebook App

I'm having issues with the webview login for Facebook on Android.
I've followed the tutorials and login works perfectly when the user has the Facebook app installed. When the Facebook app is not installed, the webview for facebook login pops up; however, after logging in and accepting the permissions, the webview simply redirects back to the login screen. It never goes back to my app.
Has anyone else encountered this problem?
FacebookSdk.sdkInitialize(this);
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
if (profile2 != null) {
loggedIn(profile2);
} else {
loggedOut();
}
}
};
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken accessToken, AccessToken accessToken2) {
Profile.fetchProfileForCurrentAccessToken();
}
};
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
getProfileInfo();
}
#Override
public void onCancel() {
// App code
Log.e("Facebook Login", "Login Cancelled");
loggedOut();
}
#Override
public void onError(FacebookException exception) {
// App code
Log.e("Facebook Login", "Failed to Login " + exception.toString());
loggedOut();
}
});
Looking at the logs without filters while the login takes place, I see a couple of possibly relevant logs.
I/chromium﹕ [INFO:CONSOLE(0)] "event.returnValue is deprecated. Please use the standard event.preventDefault() instead.", source: (0)
I/Auth.Core﹕ [TokenCache] Missing snowballing token: no granted scopes set.
What was causing the problem was that I was overriding the onclicklistener of the login button to call the login function of the LoginManager. Just don't.
I think you forgot to use callbackManager for proper workflow. Used CallbackManager for registration callback must be called in onActivityResult of host activity. Activity should not be in singleInstance launchMode because it will not be able to launch startActivityForResult(facebook internally launches FacebookActivity using this method).
So add to your activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Given your description, I am imagining that you either are not connected on the internet or that you are not handling the login callbacks.
Here is a full facebook 4.0.+ login example.
Edit Based on your code:
You need to use FacebookSdk.sdkInitialize(this); before setContentView().
This is a working example without using Facebook app and if you close your app and open it again you'll be logged in automatically unless you log out.
Here we get the user email address and friends list after log in.
public class MainActivity extends Activity {
private CallbackManager callbackManager;
private LoginButton loginButton;
private static final String TAG = "logTag";
private TextView mFriend, mEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
mFriend = (TextView) findViewById(R.id.tv_friend);
mEmail = (TextView) findViewById(R.id.tv_email);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "Successful Login");
GraphRequest friendsRequest = GraphRequest.newMyFriendsRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONArrayCallback() {
#Override
public void onCompleted(JSONArray objects, GraphResponse response) {
String x = objects.opt(0).toString();
mFriend.setText(x);
}
});
GraphRequest meRequest = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String email = response.getJSONObject().getString("email").toString();
mEmail.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email, gender");
meRequest.setParameters(parameters);
meRequest.executeAsync();
parameters = new Bundle();
parameters.putString("field", "user_friends");
friendsRequest.setParameters(parameters);
friendsRequest.executeAsync();
}
#Override
public void onCancel() {
Log.d(TAG, "Login Canceled");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "Login Error");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// manage login results
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}

Categories

Resources