Facebook API User Request graphObject is null - android

So I have an application that is currently using the facebook api to get a users info from facebook. The application has been working 100% until today when suddenly, certain info wouldnt load. I traced it back to the Facebook me request foor getting into from the current user. This is the Log of the request:
{Request: session: {Session state:OPENED, token:{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[user_birthday, basic_info]}, appId:349620835240734}, graphPath: me, graphObject: null, httpMethod: GET, parameters: Bundle[{}]}
The graph object is null and the onCompleted method is never called. As I stated before, this has been working great up until now and I have not touched this class at all. The entire request is below, and any help is GREATLY appreciated!
Request request = Request.newMeRequest(mSession, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (mSession == Session.getActiveSession()) {
if (user != null) {
String currentUserId = user.getId();
String name = user.getFirstName();
String birthday = user.getBirthday();
String age = getAge(birthday);
String gender = user.asMap().get(Constants.GENDER).toString();
mParseUser.put(Constants.NAME, name);
mParseUser.put(Constants.AGE, age);
mParseUser.put(Constants.GENDER, gender);
mParseUser.saveInBackground();
SharedPreferences pref =
mContext.getSharedPreferences(ParseUser.getCurrentUser().getUsername(),
Context.MODE_PRIVATE);
SharedPreferences.Editor ed = pref.edit();
ed.putString(Constants.FACEBOOK_USER_ID, currentUserId);
ed.apply();
}
}
}
});
Request.executeBatchAsync(request);
Log.e("RequestValue", String.valueOf(request));

Use this library when you deal with Facebook API.because it is AWESOME!! Really!..
https://github.com/sromku/android-simple-facebook
Read the docs and enjoy the library.
Tell me if it helps

Related

How to retrieve authData from a ParseUser?

I'm trying to retrieve the authData field from a ParseUser. With Parse 1.9.1, I used to do it like so:
ParseUser user = ParseUser.getCurrentUser();
HashMap authDataMap = (HashMap)user.get("authData");
HashMap facebookMap = (HashMap)authDataMap.get("facebook");
String facebookId = (String)facebookMap.get("id");
And this worked fine.
Something changed though. I don't know if it's because I updated to Parse 1.9.2 or if something changed on the Parse server side, but authData is no longer accessible. The line user.get("authData") returns null. Even if I re-fetch the user.
Ultimately I want to retrieve the Facebook id from the ParseUser, preferably without reaching out to Facebook. Is this no longer possible?
If you are using ParseFacebookUtils to perform login Facebook user then after successfully login from in parse try to get GraphUser using following to fetch Facebook user data-
Request.newMeRequest(ParseFacebookUtils.getSession(),
new Request.GraphUserCallback() {
#Override
public void onCompleted(
final GraphUser fbUser,
Response response) {
try {
if (fbUser != null
&& parseUser != null
&& fbUser.getName()
.length() > 0) {
// Facebook user data
String fbId = fbUser.getId();
} else {
// Facebook user not logged in
}
} catch (Exception e) {
e.printStackTrace();
stopLoading();
}
}
}).executeAsync();
Have you taken a look at Facebook Users section in the Parse.com documentation. I think authData is for internal communication, not meant to be called (any more).

how long is the FB postId expiration date?

I write an android application which does a FB like to a FB post.
I succeed in doing it, but after a long time I get this response:
{
Response: responseCode: 400,
graphObject: null,
error:
{
HttpStatus: 400,
errorCode: 100,
errorType: OAuthException,
errorMessage: (#100) Error finding the requested story
},
isFromCache:false
}
for the code:
Request request = new Request(
session,
takeFromPublicMacrosOrServer(currentOffer.postId)
+ "/likes", null, HttpMethod.POST,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
// Request complete
if (response.getError() == null) {
UnlockRequestToServer unlockRequestToServer = new UnlockRequestToServer(
mOffersListActivity,
PublicMacros.TYPE_UNLOCK_FB_LIKE,
currentOffer.postId);
} else {
final String errorMsg = "error: "
+ response.getError()
.toString();
Log.e(MyLogger.TAG, errorMsg);
if (BaseApplication
.getCurrentActivity() != null) {
BaseApplication
.getCurrentActivity()
.runOnUiThread(
new Runnable() {
public void run() {
if (PublicMacros.DEBUG) {
Toast.makeText(
BaseApplication
.getCurrentActivity(),
errorMsg,
Toast.LENGTH_LONG)
.show();
}
}
});
}
}
String re = response.toString();
}
});
request.executeAsync();
Does someone know how long is postId valid for FB like action ?
How do I get a page Access Token that does not expire? May contain some useful iformaion for you.
Facebook 3.0 How to post wall? Shows you how to post to your wall
This Question shows you the 'like' Facebook like in android using android.
EDIT
Facebook doesn't notify you that a previously issued access token has
become invalid. Unless you have persisted the expiry time passed to
your App along with the access token, your app may only learn that a
given token has become invalid is when you attempt to make a request
to the API. Also, in response to certain events that are
security-related, access tokens may be invalidated before the expected
expiration time.

Facebook album data returns empty in android

Facebook URL mentioned below return empty data but there is album images in Facebook, i am using new Facebook SDK 3.5.2. anyone have suggestion please help me to come out of this issue.
Thanks on advance
"https://graph.facebook.com/ID/albums?access_token=Token";
I was having the same problem. Read this. Some users dont allow access to their albums and photos through apps. You will have to code accordingly.
Session.NewPermissionsRequest np = new Session.NewPermissionsRequest(this, "friends_photos");
Session.getActiveSession().requestNewReadPermissions(np);
Request rq = new Request(Session.getActiveSession(), userID + "/albums", null, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
}
});
rq.executeAsync();
}
Here is what it should look like. just change userID to the user whose albums you want to retrieve with response being the data that is returned.
I got result by adding below this permissions but i need album list now i get only cover photo and profile picture.
if(session != null && !session.isOpened()){
OpenRequest openRequest = new OpenRequest(this).setCallback(statusCallback);
if (openRequest != null) {
openRequest.setDefaultAudience(SessionDefaultAudience.EVERYONE);
openRequest.setPermissions(Arrays.asList("friends_hometown","user_photos","friends_photos"));
openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
session.openForRead(openRequest);
}
}

Facebook SDK 3.0 - Get Facebook User ID and Access Token

I searched for past two days and was not successful in finding the method to get the user id and access token from Facebook SDK 3.0 - Native Login .
i am following facebook native login - http://developers.facebook.com/docs/tutorials/androidsdk/3.0/scrumptious/authenticate/
and i get the access token using Session.getAccessToken , i get some access token but that is not valid . what is the actual procedure ? Am i doing wrongly ?
How to get the UserId in Native Login using Facebook SDK 3.0
user id:
final Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// If the session is open, make an API call to get user data
// and define a new callback to handle the response
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
if (user != null) {
user_ID = user.getId();//user id
profileName = user.getName();//user's profile name
userNameView.setText(user.getName());
}
}
}
});
Request.executeBatchAsync(request);
}
user_ID & profileName are string.
for accessToken:
String token = session.getAccessToken();
EDITED: (13/1/2014)
for user email (i haven't check this code by running on device or emulator):
these are only my opinion or you can call it suggestion
setReadPermissions(Arrays.asList("email", ...other permission...));
//by analyzing the links bellow, i think you can set the permission in loginbutton as:
loginButton.setReadPermissions(Arrays.asList("email", ...other permission...));
user.asMap().get("email");
for more info see:
link1, link2, link3, link4,

Error OAuthException 2500 while posting with facebook graph api

I'm writting app integrated with facebook. I want to post to wall without post dialog. I try to use code from this answer, but I got an error
{"error":
{"message":"An active access token must be used to query information about the current user.",
"type":"OAuthException",
"code":2500
}
}
I login user with this code
public void authorize() {
mFacebook.authorize(mActivity, new String[] { "publish_stream" }, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", mFacebook.getAccessToken());
editor.putLong("access_expires", mFacebook.getAccessExpires());
editor.commit();
mLoginStateView.setImageResource(mAuthorizedDrawableRes);
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
Please, explain me what am I doing wrong?
[ADDED]
If I try to post with mFacebook.dialog(currentActivity, "stream.publish", params, new UpdateStatusListener()); it works. Please, help me!
A successful authorization would return an access token to your app, which you can then use to perform actions to the Facebook API. The error message displayed means you do not have a valid access token which means you probably did not authenticate the app correctly. I would put some logging on the onFacebookError and onError methods to see what the problem is.
Oh, I've done it. But it looks like a bug or magic...
LogCat after authorize method (Facebook's log is enabled)
Facebook-authorize: Login Success! access_token=AAAHL4f6XMS0BAHNJKpoGAUAeGDlynRt1s5XPdBPRWGfILGOTZB4OSEGi4HBPLZBXDWqK2RIO8disDtzxHBYSvL3bZAnHkU5hAVK9oqWhAZDZD expires=1356040438476
But then I try post with
String response = mFacebook.request("me/feed", parameters, "POST");
Function request from Facebook.java :
public String request(String graphPath, Bundle params, String httpMethod)
throws FileNotFoundException, MalformedURLException, IOException {
params.putString("format", "json");
if (isSessionValid()) {
params.putString(TOKEN, getAccessToken());
}
String url = (graphPath != null) ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL;
return Util.openUrl(url, httpMethod, params);
}
I see in debugger, that Facebook's function isSessionValid() returns false and mAccessToken = null. I don't know why it is so, and why it returns true sometimes afterwards (yes, I understand that it is impossible). Explaine me, please, if you know.
This code solved my problem (it just re-sets access token)
if (!mFacebook.isSessionValid()){
String token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
mFacebook.setAccessToken(token);
mFacebook.setAccessExpires(expires);
}
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("description", "test test test");
String response = mFacebook.request("me/feed", parameters, "POST");
if (response == null || response.equals("") || response.equals("false")) {
Log.e(Const.LOG_TAG, "Blank response");
} else {
Log.d(Const.LOG_TAG, response);
}
I also had the same problem while retrieving albums from facebook. I tested my access_token via facebook debugger and it was valid. Then I found the error, the final url in com.facebook.android.Util.openUrl(...) was:
Invalid-URL1:
https:// graph.facebook.com//me/albums?fields=id,name,cover_photo,type,count?access_token={...token..}&format=json&metadata=1
Where it should be:
Valid - URL2:
https:// graph.facebook.com//me/albums?fields=id,name,cover_photo,type,count&access_token={...token..}&format=json&metadata=1
Note that in URL1 ? is added two times which is not valid so I changed the code as follows
Code Changes:
Previous
com.facebook.android.Util.openUrl(...)
if (method.equals("GET")) {
url = url + "?" + encodeUrl(params);
}
Now
com.facebook.android.Util.openUrl(...)
if (method.equals("GET")) {
if(url.contains ( "?" )==false)
{
url = url + "?" + encodeUrl(params);
}
else
{
url = url + "&" + encodeUrl(params);
}
}

Categories

Resources