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);
}
}
Related
I want to share an image on a Facebook page of mine. But I couldn't figure out how to do this step by step. And couldn't find step by step guide for this.
This is my code to share an image on a page
Bundle params = new Bundle();
String nameText = name.getText().toString();
String tags = engine.implodeTags(tagsList);
String textText = text.getText().toString();
params.putString("caption", nameText + "\n\n" + textText + "\n\n" + tags);
params.putString("url", imagesList.get(mainImageSelected).getImageUrl());
params.putString("access_token", "{access token here}");
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/{page_id here}/photos",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
if(response.getJSONObject()!=null) {
Log.d("qwe", response.getJSONObject().toString());
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, "Shared on facebook", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
});
}
else{
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, "Error", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
});
}
}
}
).executeAsync();
It works if I put access token by hand. I am getting access token here
https://developers.facebook.com/tools/explorer .
But after some time this access token is not working any more. So I need to get new access token.
How to get PAGE access token from android itself? Via user login button of facebook sdk?
https://developers.facebook.com/docs/facebook-login/access-tokens
Please help.
Easily if you use facebook SDK to do that. read at here https://developers.facebook.com/docs/sharing/android
You need to get Permanent access token to share images on your Page. To get that you need to follow steps written here.
facebook: permanent Page Access Token?
In an Android App I have the following code:
private void requestDataFromFb() {
Callback callback = new Callback() {
#Override
public void onCompleted(Response response) {
AppLog.Log(TAG, "Facebook Response ::" + response + "");
Utility.closeprocess(Login.this);
loadImage(response);
}
};
String graphPath = "me";
Bundle bundle = new Bundle();
bundle.putString("fields",
"id,picture.height(250),gender,first_name,last_name,age_range");
Request mRequest = new Request(Session.getActiveSession(), graphPath,
bundle, HttpMethod.GET, callback);
RequestAsyncTask task = Request.executeBatchAsync(mRequest);
if (task == null) {
AppLog.Log(TAG, "task is null");
} else {
AppLog.Log(TAG, task.getStatus() + "");
}
}
It's been working fine and I am getting the paths to the user's profile picture. However, after some time the paths don't work anymore. One cannot see the picture of the first users. When I enter the URL in my browser I get:
An error occurred while processing your request.
Reference #50.3d1431b5.1424197137.a584ec67
And when using the Graph API Explorer of Facebook I get a different URL for the picture.
I do not know if that has something to do with the fact that the user has changed their profile picture or something else, and how I could solve this issue.
Any advise or guidance would be greatly appreciated
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.
I am having is issues in obtaining the public access token for my app. I am getting the following error:
05-26 14:43:17.194: D/Mobli(1219): Response {"error":"invalid_request","error_description":"The request includes an unsupported parameters","error_uri":"http://dev.mobli.com/error/invalid_request"}
The code that I am using to make the request is as follows:
Mobli mobli = new Mobli(ID, SECRET);
SampleRequestListener mobliListner = new SampleRequestListener();
runner = new AsyncMobliRunner(mobli);
runner.obtainPublicToken(mobliListner, null);
public class SampleRequestListener extends BaseRequestListner {
public void onComplete(final String response, final Object state) {
try {
// process the response here: executed in background thread
Log.d("Mobli", "Response " + response.toString());
} catch (MobliError e) {
Log.w("Mobli Error", "Error" + e.getMessage());
}
}
}
Any idea what might be wrong with the code?
I have also verified that the URL is formed correctly. I am getting the filenotfoundexcetion in util.java
Turns out there was as an issue in openUrl function in util.java that is a part of mobli sdk. In the openUrl function an extra parameter was being appended to the post request, which was resulting in the above error. Specifically, commenting out the following lines in openUrl function solved the above issue.
// use method override
if (!params.containsKey("method")) {
params.putString("method", method);
}
I am using Facebook API in my application to post messages to wall. Every thing work fine, but when I post message more than one time in a sort time interval, wall post doesn't appear on wall. I am sure there no any exception occurres while posting.
I use 'offline-access' permission with my application.
Code :
public static class UpdateWalls extends AsyncTask<String, Integer, Boolean> {
private Context context;
private String post;
public UpdateWalls(Context context, String post) {
this.context = context;
this.post = post;
}
#Override
protected Boolean doInBackground(String... strings) {
FacebookConnector facebookConnector = new FacebookConnector(Constants.FACEBOOK_APPID, context, Constants.FACEBOOK_PERMISSION);
try {
facebookConnector.postMessageOnWall(this.post);
} catch (Exception e) {
return false;
}
return true;
}
}
and FacebookConnector.postMessageOnWall() is
public void postMessageOnWall(String msg) {
if (facebook.isSessionValid()) {
Bundle parameters = new Bundle();
parameters.putString("message", msg);
try {
String response = facebook.request("me/feed", parameters,"POST");
Log.i("Facebook wall post", "While posting to wall response = " + response);
//System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
} else {
//login();
}
}
Is this a known issue or something else? Please help me.
Thank you.
The Facebook API, in most cases, won't throw exceptions even if the request fails. Error status is returned by the response to the call. In this line here:
Log.i("Facebook wall post", "While posting to wall response = " + response);
You're writing a log with the response. What is that response? What is it when the wall post succeeds compared to when it fails?
It seems facebook reject requests when they come in too fast, see this question for a short but possibly out-of-date discussion on API limits. If you're getting a response that suggests you're making too many requests, you could add a delay and try again.