I want to update status of user along with location of user in android. I have latitude, longitude and name of the location.
I have already updated status but couldn't figure out how to post it along with location.
Session session = Session.getActiveSession();
Request.Callback callback = new Request.Callback() {
#Override
public void onCompleted(Response response) {
Log.d("Checkin", response.toString());
Toast.makeText(context, response.toString(),
Toast.LENGTH_LONG).show();
}
};
if (session != null && session.isOpened()) {
Request.newStatusUpdateRequest(session,
"Posting from my fyp", null, null, callback)
.executeAsync();
}
we can do this using latest Facebook SDK:
Location location = new Location("provider");
location.setLatitude(13.1234);
location.setLongitude(13.1234);
final Session session = Session.getActiveSession();
Request placesSearchRequest = Request.newPlacesSearchRequest(session, location, 100,
1, "",
new GraphPlaceListCallback() {
#Override
public void onCompleted(List<GraphPlace> places, Response response) {
Request statusUpdateRequest = Request.newStatusUpdateRequest(session, "Hell Yea :P #fyp #success #viaCheckinApp",
places.get(0), null, new Callback() {
#Override
public void onCompleted(Response response) {
debug("response of posting checkin to facebook: " + response.toString());
}
});
statusUpdateRequest.executeAsync();
}
});
placesSearchRequest.executeAsync();
Related
I have been trying to integrate facebook to my app, but it always returns a Null Graph user.I tried adding the onActivityResult method as a solution told here, but still doesn't seem to help.
public class FacebookRegistartionActivity extends FragmentActivity
{
private Session.StatusCallback mStatusCallback = new SessionStatusCallback();
// private static final int REQUEST_CODE_SIGN_IN = 1;
Session session;
#Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
fbRegistration();
}
public void fbRegistration() {
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
session = Session.getActiveSession();
Log.i("", "Session before : "+session);
if (session == null) {
session = new Session(FacebookRegistartionActivity.this);
if (session != null) {
Session.setActiveSession(session);
if (session != null && !session.isOpened()&& !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(mStatusCallback));
} else {
}
}
} else {
Log.i("", "Session null ... : "+session);
// start Facebook Login
Session.openActiveSession(this, true, mStatusCallback);
}
}
The code doesn't even reach the onActivityResult() method.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Log.i("", "requestCode : "+requestCode);
Log.i("", "resultCode : "+resultCode);
Log.i("", "data : "+data);
if (resultCode == RESULT_OK) {
Session.getActiveSession().onActivityResult(this, requestCode,resultCode, data);
}
}
private class SessionStatusCallback implements Session.StatusCallback {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
Log.i("", "session in on status call back....."+session);
// Here the session is there, not null
if (session.isOpened()) {
Log.i("", "session is opened....."+session.isOpened());
// make request to the /me API
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(final GraphUser user, Response response) {
Log.i("in SignUp", "USER :: " + user);
// Log.i("in SignUp", "response :: " + response);
if (user != null) {
try{
String fqlQuery = "select url from profile_pic where id=me() and width=200 and height=200";
Bundle params1 = new Bundle();
params1.putString("q", fqlQuery);
Session session = Session.getActiveSession();
Request request = new Request(session, "/fql", params1,
HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
try {
String serverresponse=response.getGraphObject().getInnerJSONObject().toString();
Log.e("serverresponse", ""+serverresponse);
JSONObject jsonobj=new JSONObject(serverresponse);
JSONArray array=jsonobj.getJSONArray("data");
Log.e("","data object : "+array);
jsonobj = array.getJSONObject(0);
String fbUserImageUrl = jsonobj.getString("url");
Log.e("","image url : "+fbUserImageUrl);
Logger.show(Log.INFO, "", " AccessToken with publish stream:: " +Session.getActiveSession().getAccessToken());
String uniqueId = user.getId();
String userName = user.getName();
String image = fbUserImageUrl; //"http://graph.facebook.com/"+user.getId()+"/picture?type=large";
String emailId = user.asMap().get("email").toString();
Logger.show(Log.INFO,"","uniqueId :: "+ uniqueId);
Logger.show(Log.INFO,"","userName :: "+ userName);
Logger.show(Log.INFO,"","image :: "+ image);
Logger.show(Log.INFO,"","emailId :: "+ emailId);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
Request.executeBatchAsync(request);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
else
{
Log.i("", "Graph user null");
// Always the Graph user is returning Null
}
}
}).executeAsync();
}
else
{
Log.i("", "Session not opened still.....");
}
}
}
}
EDIT :
I checked for answers, then realized, I just missed to add the permissions into the Android Manifest file.
Just realized! I Did everything except adding the following permission in Android Manifest file.
<uses-permission android:name="android.permission.INTERNET" />
But, Still wonder how I was able to get the session. Means, it does not require a net connection? Taken in to account that the device I tested had the facebook app installed in it.
Is the session provided by the facebook app, instead? Wished to know how the facebook app works in the login flow in our app, using the facebook sdk.
Any help regarding this is appreciated.
As I have mentioned in comment - Yes it is true that when a facebook Session object is created, it attempts to initialize itself from a TokenCachingStrategy. But there must be a Session token cache. As you have told that you were using same app id from some other app, the app was authorized by the user and the session was created and saved in the cache.
Because facebook manages session based on the app id and as the session was already created it fetched it from cache for your new app. But for fetching graph user when you call Request.newMeRequest, it is making an internet connection, since the internet permission was not there in the manifest, your app was not able to connect to facebook server to fetch the same.
I am working on Facebook integration in my application:
But something going wrong and the email address of the user always returns null value:
Here is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
..
..
//initiate session
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
Session.OpenRequest op = new Session.OpenRequest(this);
op.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
op.setCallback(null);
List<String> permissions = new ArrayList<String>();
permissions.add("publish_stream");
permissions.add("user_likes");
permissions.add("email");
permissions.add("user_birthday");
op.setPermissions(permissions);
Session.setActiveSession(session);
session.openForPublish(op);
}
}
}
#Override
public void onStart() {
Logger.d(TAG,"onStart");
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}
#Override
public void onStop() {
Logger.d(TAG,"onStop");
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Logger.d(TAG,"onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Logger.d(TAG,"onSaveInstanceState");
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
private void getUserDetails(Session session) {
Logger.d(TAG,"getUserDetails");
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
Log.d(TAG,"newMeRequest:onCompleted");
if (user != null) {
fbCurrentUser = user;
Log.d(TAG,"Already logged-in : "+ user.getId());
Log.d(TAG,"User First Name: "+ user.getFirstName());
Log.d(TAG, "User Email: " + user.getProperty("email"));
Log.e(TAG, "response: " + response);
Log.e(TAG, "user: " + user.toString());
//check if new user [get his friends list]
getFriendsList();
} else {
Log.e(TAG,"No User Found");
}
}
});
Request.executeBatchAsync(request);
}
Please Help!
Thanks in advance!
Check the response giving any error or not then
JSONObject json = com.facebook.android.Util.parseJson(response);
if(json != null){
final String id = json.getString("id");
final String email = json.getString("email");
}
Try this for getting email,
String email = user.asMap().get("email").toString();
Log.d(TAG, "User Email: " + email);
TextView mEmail = (TextView) findViewById(R.id.textView1);
mEmail.setText(email);
or else give a try to below code
Log.d(TAG, "User Email: " + user.getProperty("email").toString());
just add toString() at end of Log for more reference check this link
With this above piece of code i am successfully able to get the user's email.
Edit
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
String email = user.asMap()
.get("email").toString();
mEmail.setText(email);
}
}
});
} else {
Toast.makeText(getApplicationContext(), "Error...",
Toast.LENGTH_LONG);
}
}
});
Hello fellow programmers, I having difficulties on the new Facebook SDK,
Scenario is:
im using fragment so I follow this steps
Why doesn't Android Facebook interface work with Fragments?
and now Im getting the oncomplete and the token ID
Now I want to post on my wall so ive created this function
private void publishStory(Session session) {
if (session != null){
// Check for publish permissions
session.addCallback(new StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
List<String> PERMISSIONS = Arrays
.asList("publish_actions");
session
.requestNewPublishPermissions(new Session.NewPermissionsRequest(
getActivity(), PERMISSIONS));
Request request = Request.newStatusUpdateRequest(
session, "Temple Hello Word Sample",
new Request.Callback() {
#Override
public void onCompleted(Response response) {
Log.i("fb:done = ", response.getGraphObject() + ","
+ response.getError());
}
});
request.executeAsync();
}
});
And put the Declaration on the Oncomplete
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
publishStory(session);
}
else
{
Log.v("FACEBOOK ", "NO ACCESS");
}
}
});
}
My problem is on this line of code session.addCallback(new StatusCallback() { it skips the next step thus ending the function without posting on my wall.
I am quite sure that the session is active as I have applicationID and access token..
Any Help?
Thanks
EDIT
Im using this code based on the Answer below and added new permissions
private void publishStoryTEST(final Session session)
{
if (session != null)
{
Bundle postParams = new Bundle();
postParams.putString("message", "TEST");
Request.Callback callback = new Request.Callback()
{
public void onCompleted(Response response)
{
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try
{
postId = graphResponse.getString("id");
}
catch (JSONException e)
{
Log.i("JSON", "JSON error " + e.getMessage());
}
FacebookRequestError error = response.getError();
Log.e("post response", response.toString());
if (error != null)
{
}
else
{
}
}
};
List<String> PERMISSIONS = Arrays
.asList("publish_actions");
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(getActivity(), PERMISSIONS));
Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
But still Im getting an error saying
The user hasn't authorized the application to perform this action
Why is that I still get that error? Does the permission never called?
The problem is common, i am sharing with you the working source code of the Posting Method that i am currently using in my Application.
private void publishStory(String status)
{
Session session = Session.getActiveSession();
if (session != null)
{
Bundle postParams = new Bundle();
postParams.putString("message", status);
Request.Callback callback = new Request.Callback()
{
public void onMalformedURLException(MalformedURLException e)
{
}
public void onIOException(IOException e)
{
}
public void onFileNotFoundException(FileNotFoundExceptione)
{
}
public void onFacebookError(FacebookError e)
{
}
public void onCompleted(Response response)
{
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try
{
postId = graphResponse.getString("id");
}
catch (JSONException e)
{
Log.i("JSON", "JSON error " + e.getMessage());
}
FacebookRequestError error = response.getError();
Log.e("post response", response.toString());
if (error != null)
{
}
else
{
}
}
};
Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
I hope this solves your problem.
EDIT:
Please refer to the following links, for a detailed procedure of setting up Facebook SDK 3.0 with proper permissions and posting features.
Post to facebook after login fails Android
http://www.kpbird.com/2013/03/android-login-using-facebook-sdk-30.html
// Try below code
private void postData() {
lnrPbr.setVisibility(View.VISIBLE);
isSharingData = true;
Session session = Session.getActiveSession();
if (session != null) {
Bundle postParams = new Bundle();
postParams.putString("name", getIntent().getStringExtra("IN_SHARE_CAPTION") == null ? "" : getIntent().getStringExtra("IN_SHARE_CAPTION"));
postParams.putString("caption", getIntent().getStringExtra("IN_SHARE_CAPTION") == null ? "" : getIntent().getStringExtra("IN_SHARE_CAPTION"));
postParams.putString("description", getIntent().getStringExtra("IN_SHARE_DESCRIPTION") == null ? "" : getIntent().getStringExtra("IN_SHARE_DESCRIPTION"));
postParams.putString("link", getIntent().getStringExtra("IN_SHARE_SHARELINK") == null ? "" : getIntent().getStringExtra("IN_SHARE_SHARELINK"));
postParams.putString("picture", getIntent().getStringExtra("IN_SHARE_THUMB") == null ? "" : getIntent().getStringExtra("IN_SHARE_THUMB"));
postParams.putString("message", getIntent().getStringExtra("IN_SHARE_MESSAGE") == null ? "" : getIntent().getStringExtra("IN_SHARE_MESSAGE"));
Request.Callback callback = new Request.Callback() {
public void onCompleted(Response response) {
isSharingData = false;
lnrPbr.setVisibility(View.GONE);
FacebookRequestError error = response.getError();
if (error != null) {
IjoomerUtilities.getCustomOkDialog(getString(R.string.facebook_share_title), error.getErrorMessage(), getString(R.string.ok), R.layout.ijoomer_ok_dialog, new CustomAlertNeutral() {
#Override
public void NeutralMethod() {
finish();
}
});
} else {
IjoomerUtilities.getCustomOkDialog(getString(R.string.facebook_share_title), getString(R.string.facebook_share_success), getString(R.string.ok), R.layout.ijoomer_ok_dialog, new CustomAlertNeutral() {
#Override
public void NeutralMethod() {
finish();
}
});
}
}
};
Request request = new Request(Session.getActiveSession(), "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
Refer this tutorial..
http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
I want to implement "Like" and "Comment" feature in my app. I used this code:
public static void like(String postID) {
String grapPath = String.format("%s/likes", postID);
Request request = new Request(Session.getActiveSession(), grapPath,
null, HttpMethod.POST, new Callback() {
#Override
public void onCompleted(Response response) {
Log.i(TAG, response.toString()+" Success!");
}
});
Request.executeBatchAsync(request);
}
public static void postComment(String comment, String postID) {
String grapPath = String.format("%s/comments", postID);
Bundle bundle = new Bundle();
bundle.putString("message", comment);
Request request = new Request(Session.getActiveSession(), grapPath,
bundle, HttpMethod.POST, new Callback() {
#Override
public void onCompleted(Response response) {
Log.i(TAG, "Success!");
}
});
Request.executeBatchAsync(request);
}
Hhow and where can I call these methods to make them work?
Please make sure the prerequisites are set up correctly. Specifically check out the middle of step 4 to make sure you generated your key hash correctly using your debug keystore.
Otherwise code below should help out
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}
private void postStatusUpdate() {
if (hasPublishPermission()) {
final String message = "Posting to facebook";
Request request = Request
.newStatusUpdateRequest(Session.getActiveSession(), message, place, tags, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(message, response.getGraphObject(), response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
I'm trying to get the user email and birthday (using a Me request). My app has email and user_birthday permissions and the fb account i'm using has an email and a birthday set.
When I try using the 'Graph API Explorer' (https://developers.facebook.com/tools/explorer) using the user access_token with 'fields=id,email,birthday' all I get is the id.
Can anybody advice me on this please.
Here is my code:
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// here I check the infos I got.
Log.d("some tag", user.getInnerJSONObject().toString()); // it shows only the id, no email or birthday.
if (Session.getActiveSession() != null) {
Log.i(TAG, "Log out from FB");
Session.getActiveSession().closeAndClearTokenInformation();
}
}
}
});
// set params.
request.getParameters().putString("fields", "id,email,birthday");
// execute request.
request.executeAsync();
Log.d(TAG, request.toString());
}
if (exception != null) {
exception.printStackTrace();
}
}
});
Many thanks.
I finally changed the approach using the OpenRequest instead of getMeRequest:
Here is my code:
public void onClick(View v) {
Logger.d(TAG, "Start FB session");
// check if a session exists.
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
// create a new session.
Session session = new Session.Builder(getApplicationContext()).build();
// set it a the active session.
Session.setActiveSession(session);
// keep a variable link to session.
currentSession = session;
}
// if a session is already open then issue a request using the available
// session. Otherwise ask for user credentials.
if (currentSession.isOpened()) {
// The user is logged in.
Logger.e(TAG, "User is logged in.");
Session.getActiveSession().closeAndClearTokenInformation();
Logger.i(TAG, "Session closed an token information cleared.");
// get user data here with no extra call.
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Logger.i(TAG, "User:" + user.getInnerJSONObject());
}
}
});
}
}
});
} else {
// Ask for username and password
OpenRequest op = new Session.OpenRequest((Activity) this);
// don't use SSO.
op.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
// no callback needed.
op.setCallback(null);
// set permissions.
List<String> permissions = new ArrayList<String>();
permissions.add("email");
permissions.add("user_birthday");
op.setPermissions(permissions);
// open session for read.
currentSession.openForRead(op);
Logger.d(TAG, "Session open for read request issued.");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Logger.d(TAG, "Request code is: " + requestCode);
Logger.d(TAG, "Result code is: " + resultCode);
super.onActivityResult(requestCode, resultCode, data);
if (Session.getActiveSession() != null)
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(getApplicationContext()).build();
Session.setActiveSession(session);
currentSession = session;
}
if (currentSession.isOpened()) {
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Logger.i(TAG, "User:" + user.getInnerJSONObject());
}
}
});
}
}
});
}
}
I hope this helps.
When you are using Request.GraphUserCallback(), its best to use it in MAIN UI THREAD
Session s = Session.getActiveSession();
if(s!=null)
{
Request.executeMeRequestAsync(s,new Request.GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
if(user!=null)
{
try {
String fbid=null;
String birthday=null;
fbid=user.getId();
birthday=user.getBirthday();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
});
}
you can try this also before the Request.executeMeRequestAsync(...){...}
List<String> permissions = session.getPermissions();
List<String> permissionsBirthday = new ArrayList<String>();
permissionsBirthday.add("user_birthday");
if (!isSubsetOf(permissionsBirthday, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, permissionsBirthday);
if (setPermissions(session, newPermissionsRequest))
return;
}
the method isSubsetOf();
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
hope this helps.
This code worked for me hope you find it useful. This retrieves the user email in 3 different ways and also logs it
try{
// new Read().execute("Facebook");
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// TextView welcome = (TextView) findViewById(R.id.welcome);
// welcome.setText("Hello " + user.getName() + "!");
Log.d("useremai", (String) user.getProperty("email"));
Log.d("USER", user.getInnerJSONObject().toString());
JSONObject details = user.getInnerJSONObject();
useremail = details.optString("email");
Log.d("name", user.getName());
Log.d("email", useremail);
}
}
});
}
}
});
}catch(NoClassDefFoundError e){
e.printStackTrace();
}
Try this one:
if you have object of user than do below:
if (user != null) {
String UserId = user.getId();
try {
Log.i("Birthdate", ""+user.getInnerJSONObject().getString("birthday"));
} catch (JSONException e) {
e.printStackTrace();
}
}