How do I publish a check in to facebook with android SDK - facebook

The docs are terrible. I want to publish a users check in to facebook. According to the docs creating a checkin object is deprecated
https://developers.facebook.com/docs/reference/api/checkin
and instead you're supposed to add a post with location data attached. So that's what I'm trying to do. Or maybe i'm supposed to try to publish and open graph story?
Anyways here's what I have, it's basically the code to publish a post that is in their SDK sample, the post is created but there is no location data attached.
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null) {
Bundle placeBundle = new Bundle();
Bundle locationBundle = new Bundle();
Bundle postParams = new Bundle();
locationBundle.putString("latitude",String.valueOf(place.getLat()));
locationBundle.putString("longitude",String.valueOf(place.getLng()));
placeBundle.putString("id", place.getPage_id());
placeBundle.putString("name", place.getName());
placeBundle.putBundle("location", locationBundle);
postParams.putBundle("place", placeBundle);
postParams.putString("message", "test message");
Request.Callback callback = new Request.Callback() {
public void onCompleted(Response response) {
String postId = null;
try {
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
postId = graphResponse.getString("id");
}
catch (JSONException e) {
Log.i(app.TAG, "JSON error " + e.getMessage());
}
catch(Exception e){
e.printStackTrace();
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(mContext, error.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(mContext, postId, Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
else {
toast("no session to publish");
}
}
the session does have publish permissions and it WILL publish a post but all that is there is the "test message" string. The place object is from facebook's servers so it is an actual place with a page_id. When i'm debugging the post params look something like this
Bundle[{message=test message, place=Bundle[{id=171229079554355, location=Bundle[{longitude=-122.434568, latitude=37.797314}], name=The Brixton San Francisco}]}]

Session.openActiveSession(activity, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session != null && session.isOpened()) {
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
activity, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
Bundle postParams = new Bundle();
postParams.putString("message", message);
postParams.putString("tags",tag);
postParams.putString("place",place_id);
Request.Callback callback = new Request.Callback() {
private String toastmessage;
public void onCompleted(Response response) {
try {
JSONObject graphResponse = response
.getGraphObject().getInnerJSONObject();
String postId = null;
postId = graphResponse.getString("id");
} catch (Exception e) {
Log.i("Test", "JSON error " + e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
isPosted(false);
Toast.makeText(
activity.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
isPosted(true);
toastmessage = "Posted Successfully";
Toast.makeText(activity, toastmessage,
Toast.LENGTH_SHORT).show();
{
}
}
}
};
Request request = new Request(session, "me/feed",
postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
});

Related

Unity occurs a 400 Bad Request when calling a HTTP-Post on an SAP Rest API

I want to call a REST API with an Unity-Script but it occurs me the Error 400 Bad Request. It is maybe because of the http-header. May you can help me. SAP offers a Code Snippet in JAVA which I want to show you first:
DataOutputStream dataOut = null;
BufferedReader in =null;
try {
//API endpoint for API sandbox
String url = "https://sandbox.api.sap.com/mlfs/api/v2/image/scene-text-
recognition";
//Available API Endpoints
//https://mlfproduction-scene-text-
recognition.cfapps.eu10.hana.ondemand.com/api/v2/image
//https://mlfproduction-scene-text-
recognition.cfapps.us10.hana.ondemand.com/api/v2/image
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection)
urlObj.openConnection();
//setting request method
connection.setRequestMethod("POST");
//adding headers
connection.setRequestProperty("content-type","multipart/form-data;
boundary=---011000010111000001101001");
//API Key for API Sandbox
connection.setRequestProperty("APIKey","----api-Key---");
//Available Security Schemes for productive API Endpoints
//OAuth 2.0
connection.setDoInput(true);
//sending POST request
connection.setDoOutput(true);
dataOut = new DataOutputStream(connection.getOutputStream());
dataOut.writeBytes("-----011000010111000001101001\r\nContent-
Disposition: form-data; name=\"files\"; filename=\"<file_name>\"\r\nContent-Type: <file_type>\r\n\r\n<file_contents>\r\n-----011000010111000001101001--");
dataOut.flush();
int responseCode = connection.getResponseCode();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
//printing response
System.out.println(response.toString());
} catch (Exception e) {
//do something with exception
e.printStackTrace();
} finally {
try {
if(dataOut != null) {
dataOut.close();
}
if(in != null) {
in.close();
}
} catch (IOException e) {
//do something with exception
e.printStackTrace();
}
}
My UnityCode looks something like this:
public void ExecutePost()
{
Debug.Log("execute started");
byte[] img =
File.ReadAllBytes(#"C:\Users\InnovationLab\Documents\ECENTA\ECENTA
FSE\Bild1.jpg");
string url = "https://sandbox.api.sap.com/mlfs/api/v2/image/scene-
text-recognition";
coroutine = Post(url, img);
StartCoroutine(coroutine);
}
public IEnumerator Post(string url,byte[] image)
{
WWWForm form = new WWWForm();
form.AddBinaryData("imageField", image, "HoloImg");
var headers = new Dictionary<string, string> {
{"content-type", "multipart/form-data; boundary=---011000010111000001101001" },
{"APIKey", "---here I implemented the key---" }
};
WWW www = new WWW(url, image, headers);
yield return www;
if (www.error != null && www.error != "")
{ // on error, show information and return
Debug.Log("Network Error occured: " + www.error);
yield break;
}
while (!www.isDone)
{
Debug.Log(www.text);
}
}
}
So my question is, how to change the unity code so that it works?
I fixed it by using MultipartFormSections. The problem was that the api expected form-data not a binary Array.
public IEnumerator Upload(string url, byte[] img)
{
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
MultipartFormFileSection myFormFile = new MultipartFormFileSection("files", img,
"Bild1.jpg", "multipart/form-data");
formData.Add(myFormFile);
Debug.Log(formData.ToString());
UnityWebRequest www = UnityWebRequest.Post(url, formData);
www.SetRequestHeader("APIKey", "<api-key>");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
throw new Exception(www.downloadHandler.text ?? www.error);
}
else
{
Debug.Log("Done!!!!!");
}
Debug.Log(www.downloadHandler.text);
var ResultObject = JsonUtility.FromJson<TextPrediction>(www.downloadHandler.text);
foreach (var result in ResultObject.texts)
{
}
}

Parse and Facebook SDK accessToken return null

I'm trying to extract information using the Facebook Graph Api along with Parse API. When calling the Graph API, The GraphRepsone is null. The problem is because the accessToken is null but I can't figure out how to fix after trying many different ways.
buttonSignUpWithFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// this is where you can begin doing facebook sign up process
Log.i(TAG, "did click on facebook button");
List<String> permissions = Arrays.asList("user_location", "user_friends", "email", "public_profile");
ParseFacebookUtils.logInWithReadPermissionsInBackground(SignUpActivity.this, permissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("App", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d("App", "User signed up and logged in through Facebook!");
startActivity(new Intent(SignUpActivity.this, Home.class));
} else {
Log.d("App", "User logged in through Facebook!");
setupUser();
startActivity(new Intent(SignUpActivity.this, Home.class));
}
}
public void setupUser() {
accessToken = AccessToken.getCurrentAccessToken();
}
});
GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
if (response != null) {
try {
String email = object.getString("email");
String firstName = object.getString("first_name");
Log.d(TAG, "first name " + firstName);
} catch (JSONException e) {
e.printStackTrace();
}
// String firstName = jsonResponseObject.getFirstName();
// String lastName = jsonResponseObject.getLastName();
}
}
});
Bundle param = new Bundle();
param.putString("fields","cover, birthday, email, first_name, last_name, ");
request.setParameters(param);
request.executeAsync();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
}
I'd hate to give a vague answer, but I don't think the problem is in the code snippet. I suggest you revise your steps and make sure you followed these links completely again:
https://developers.facebook.com/docs/android/getting-started
https://parse.com/docs/android/guide#users-facebook-users

Android app facebook login integration to display username, email id and profile photo

In Android app I have integrated Facebook login in android studio. I want to display username, user email id and a user profile photo after login. How will I get it?
Use this for user information. Its work successfully.
loginButton = (LoginButton) findViewById(R.id.login_button);
List < String > permissionNeeds = Arrays.asList("user_photos", "email",
"user_birthday", "public_profile", "AccessToken");
loginButton.registerCallback(callbackManager,
new FacebookCallback < LoginResult > () {#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("onSuccess");
String accessToken = loginResult.getAccessToken()
.getToken();
Log.i("accessToken", accessToken);
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
Log.i("LoginActivity", response.toString());
try {
id = object.getString("id");
try {
URL profile_pic = new URL(
"http://graph.facebook.com/" + id + "/picture?type=large");
Log.i("profile_pic",
profile_pic + "");
} catch (MalformedURLException e) {
e.printStackTrace();
}
name = object.getString("name");
email = object.getString("email");
gender = object.getString("gender");
birthday = object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields",
"id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
System.out.println("onCancel");
}
#Override
public void onError(FacebookException exception) {
System.out.println("onError");
Log.v("LoginActivity", exception.getCause().toString());
}
});
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent data) {
super.onActivityResult(requestCode, responseCode, data);
callbackManager.onActivityResult(requestCode, responseCode, data);
}

Using PageManager API in AEM6/CQ5

My requirement is to iterate over 8000 nodes in the JCR and create a Page object in Java for each node using PageManager API.
To start with I am using PageManager to get the title of a Page as below.
public String currentPageTitle(String pagePath) {
Page page=null;
ResourceResolver resourceResolver=null;
PageManager pageManager=null;
try {
if (pagePath != null) {
resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
pageManager = resourceResolver.adaptTo(PageManager.class);
**page = pageManager.getContainingPage(resourceResolver.getResource(pagePath));**
LOGGER.error("Page $$$$"+page);
if (page == null) {
throw new IllegalArgumentException("Page does not exist: " + pagePath);
}
}
} catch (LoginException e) {
LOGGER.error("Login Exception");
e.printStackTrace();
}
return page.getTitle();
}
Here I am getting page object as null, and it's throwing "Page does not exist: /content/geometrixx/fr.html" when i am trying to pass Geometrixx page URL to get its title.
Remove Extension(.html) and Execute.It will work Fine.
For Iteration over 80000 pages use Recursive function .
public String currentPageTitle(String pagePath) {
Page page=null;
ResourceResolver resourceResolver=null;
PageManager pageManager=null;
try {
if (pagePath != null) {
resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
pageManager = resourceResolver.adaptTo(PageManager.class);
page = pageManager.getContainingPage(resourceResolver.getResource(pagePath));
LOGGER.error("Page $$$$"+page);
if (page == null) {
throw new IllegalArgumentException("Page does not exist: " + pagePath);
}else{
buildLinkAndChildren_loop(page);
}
}
} catch (LoginException e) {
LOGGER.error("Login Exception");
e.printStackTrace();
}
return page.getTitle();
}
public void buildLinkAndChildren_loop(Page page) {
if (page != null) {
Iterator<Page> children = page.listChildren();
while (children.hasNext()) {
Page child = children.next();
buildLinkAndChildren_loop(child);
}
}
}

Tag friend in wallpost with Android Facebook sdk

I'm trying to tag a friend in a wallpost using the android facebook sdk. However, what is supposed to be the tag, is blank, nothing. This is the code I've used:
Bundle params = new Bundle();
access_token = fb.getAccessToken();
try {
params.putString("format", "json");
params.putString("access_token", access_token);
String url = "https://graphs.facebook.com/me/friends";
String response = Util.openUrl(url, "GET", params);
JSONObject json = Util.parseJson(response);
JSONArray array = json.optJSONArray("data");
for(int i = 0; i < array.length(); i++) {
String tempName = array.getJSONObject(i).getString("name");
String tempID = array.getJSONObject(i).getString("id");
//Probably should have some if-tests here
if(tempName.contains(*nameOfFriend*)) {
Bundle bundle = new Bundle();
bundle.putString("message", "App tagging test");
//this is where the tagging is supposed to happen
bundle.putString("tags", *UserID*);
try {
fb.request("me/feed", bundle, "POST");
Toast.makeText(getApplicationContext(), "Tag-test", Toast.LENGTH_SHORT).show();
} catch (MalformedURLException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Couldn't find friend", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I've only granted the permission for "publish_stream", could it be that I need other permissions?
Thanks in advance for any help, guys!
Following is the working code to tag friends
Also you have to submit your review to fb for the Taggable Friends api feature of the project you created in the devlepoer facebook account.After you get the approval for your submission the following code will tag your friends.
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, facebook.getAccessToken());
params.putString("method", "photos.upload");
params.putString("caption", ShareTripActivity.tripNotes); // text to post
if(ShareTripActivity.arr_facebookID.size()>0)
{
String tagFriendListId="";
for(int i=0;i<ShareTripActivity.arr_facebookID.size();i++)
{
tagFriendListId = tagFriendListId+"{'tag_uid':'"+ShareTripActivity.arr_facebookID.get(i)+"'} ,";
}
tagFriendListId=tagFriendListId.substring(0, tagFriendListId.length()-1);
params.putString("tags","["+tagFriendListId+"]");
}
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
//sample upload listener
public class SampleUploadListener extends BaseKeyListener implements RequestListener
{
public void onComplete(final String response, final Object state)
{
try
{
// process the response here: (executed in background thread)
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String src = json.getString("src");
// then post the processed result back to the UI thread
// if we do not do this, an runtime exception will be generated
// e.g. "CalledFromWrongThreadException: Only the original
// thread that created a view hierarchy can touch its views."
}
catch (JSONException e)
{
Log.w("Facebook-Example", "JSON Error in response");
}
catch (FacebookError e)
{
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
public void onFacebookError(FacebookError e, Object state)
{
// TODO Auto-generated method stub
}
public Bitmap getInputType(Bitmap img)
{
// TODO Auto-generated method stub
return img;
}
public int getInputType()
{
// TODO Auto-generated method stub
return 0;
}
public void onIOException(IOException e, Object state)
{
// TODO Auto-generated method stub
}
public void onFileNotFoundException(FileNotFoundException e, Object state)
{
// TODO Auto-generated method stub
}
public void onMalformedURLException(MalformedURLException e, Object state)
{
// TODO Auto-generated method stub
}
}
In this arr_facebookID is the arraylist containing the facebook_user_id of your friends whom you are going to tag.
I can’t see any value for place in your code, but that is required when tagging people in posts made via the API.
https://developers.facebook.com/docs/reference/api/user/#posts:
tags […] NOTE: You cannot specify this field without also specifying a place.