facebook sharing shows nullpointer exception at jsonobject graphresponse - android

I want to publish link if the user is logged in facebook and if not make user logged in and then publish link but it shows NullPointerException at jsonobject graphresponse in the publishlink() method.
Following is my code..
public static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
public static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
public boolean pendingPublishReauthorization = false;
private Session.StatusCallback statusCallback = new SessionStatusCallback();
public void ShareOnFacebook(String sharingpath)
{
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(getBaseContext()).build();
Session.setActiveSession(session);
currentSession = session;
}
else if (!currentSession.isOpened()) {
// Ask for username and password
OpenRequest op = new Session.OpenRequest(this);
op.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
op.setCallback(statusCallback);
List<String> permissions = new ArrayList<String>();
permissions.add("publish_stream");
op.setPermissions(permissions);
Session session = new Session(this);
Session.setActiveSession(session);
Log.d("session", "opening sesion for publish action!!");
session.openForPublish(op);
}
}
private class SessionStatusCallback implements Session.StatusCallback
{
#Override
public void call(final Session session, SessionState state, Exception exception)
{
//we have callback here
if (session.isOpened())
{
Log.d("session", "session is already opened ,we are in the callback section...going to publish link!!");
PublishLink();
}
}
}
public void PublishLink()
{
SharedPreferences prefs = getSharedPreferences("shared",MODE_PRIVATE);
String path = prefs.getString("path", "");
Session session = Session.getActiveSession();
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this,PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
}
Bundle postParams = new Bundle();
postParams.putString("link", path);
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
Log.d("graphresponse", response.toString());
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.d(
"JSON error "+ e.getMessage(), postId);
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(
getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
getApplicationContext(),
postId,
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
public boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
Log.d("data", "data coming to onactivityresult: "+data);
}

The problem here is that the requestNewPublishPermissions() method is an asynchronous request, and when you call it, it returns immediately, but at that point, you don't have the publish permissions yet.
What you're doing is making a "publish" request, regardless of whether you have the publish permissions yet, and so the response is going to have an error rather than a GraphObject result.
If you check the response.getError(), you'll likely see a permission error (you should always check that first, before accessing anything else in the Response).
Have a look at the HelloFacebook sample on how to temporarily cache the information you want to post (while you wait for the requestNewPublishPermissions to finish), and only post when you have all the permissions necessary.

finally figured out there was error in
Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
so change it to
Request request = Request.newStatusUpdateRequest(session, path, callback);
hope this helps someone who have this problem.
so we donot need to create new Bundle anymore ....
we can remove create Bundle and postparams.putString lines in above code..

Related

Fb not providing Login info to users that are not listed in app's role as admin or tester

I have a confusable situation here. In my android app, I am using Fb login and SDK.Things work fine when fb native app is not present.But when fb app is there and login is done then FB provides info only when I logged on with native FB app and not when somebody else logins. The screen just flashes once and goes away. I have also found that roles that are listed in app on fb including me (admin) & testers are able to fetch information, but not the other normal users. I have tried but I dont know where the fault is happening?
thanks.
public void signInWithFacebook() {
Constant.printKeyHash(MainActivity.this);
mSessionTracker = new SessionTracker(mContext, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
}
}, null, false);
String applicationId = Utility.getMetadataApplicationId(mContext);
Constant.mCurrentSession = mSessionTracker.getSession();
if (Constant.mCurrentSession == null || Constant.mCurrentSession.getState().isClosed()) {
mSessionTracker.setSession(null);
Session session = new Session.Builder(mContext).setApplicationId(applicationId).build();
Session.setActiveSession(session);
Constant.mCurrentSession = session;
} else {
mSessionTracker.setSession(null);
Session session = new Session.Builder(mContext).setApplicationId(applicationId).build();
Session.setActiveSession(session);
Constant.mCurrentSession = session;
}
if (!Constant.mCurrentSession.isOpened()) {
Session.OpenRequest openRequest = null;
openRequest = new Session.OpenRequest((Activity) mContext);
if (openRequest != null) {
openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
openRequest.setPermissions(Arrays.asList("user_birthday", "email", "user_location", "user_friends"));
openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
Constant.mCurrentSession.openForRead(openRequest);
try {
// progressfb.show();
// progressfb.setCancelable(false);
}
catch (Exception e)
{
}
accessFacebookUserInfo();
}
} else {
// progressfb.show();
accessFacebookUserInfo();
}
}
public void accessFacebookUserInfo() {
if (Session.getActiveSession() != null || Session.getActiveSession().isOpened()) {
Bundle bundle = new Bundle();
bundle.putString("fields", "picture,email,first_name, last_name, name");
// bundle.putString("fields", "email");
// bundle.putString("fields", "first_name");
final Request request = new Request(Session.getActiveSession(), "me", bundle, HttpMethod.GET, new Request.Callback() {
#SuppressWarnings("unused")
#Override
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
if (graphObject != null) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject = graphObject.getInnerJSONObject();
Log.i("", "faacebook response===" + jsonObject.toString());
String facebook_id = jsonObject.getString("id");
JSONObject picture_obj = jsonObject.getJSONObject("picture");
JSONObject picture_data = picture_obj.getJSONObject("data");
// fb_pic_url = picture_data.getString("url");
String first_name = jsonObject.getString("name");
String last_name = jsonObject.getString("last_name");
String socialName = jsonObject.getString("name");
eemail = jsonObject.getString("email");
String fb_pic_url = "https://graph.facebook.com/"
+ facebook_id
+ "/picture?type=large";
new fbSigninActivity().execute(eemail,first_name);
callFacebookLogout(MainActivity.this);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(mContext, "something went wrong", Toast.LENGTH_LONG).show();
}
}
}
});
Request.executeBatchAsync(request);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// com.facebook.Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
if (Constant.mCurrentSession.isOpened()) {
accessFacebookUserInfo();
} else {
//Utils.showCenterToast(contxt, getResources().getString(R.string.msg_went_wrong));
}
} else {
Constant.mCurrentSession = null;
mSessionTracker.setSession(null);
// progressfb.dismiss();
}
}
The issue is happening because the feature you are trying to use needs to be approved by Facebook first. You must submit an APK for them to test. Anyone listed as an Admin, Developer, or Tester of your app should work fine (you may need to add their debug hash of the device to the list). But until your app gets approved by Facebook to use specific features or Graph Calls normal users will NOT be able to use it.

(#200) response The user hasn't authorized the application to perform this action

I'm implementing facebook in my apps. Login with no problem through facebook managed to get the response from it. When try to post feed the error state as below: i tried many way all not working. please help me.
public class main extends Activity{
static Session session;
Activity aty;
Context context;
protected static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
protected boolean pendingPublishReauthorization = false;
private FacebookloginDelegate delegate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
publishFeedDialog();
}
public void loginWithFacebook() {
// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
// TODO Auto-generated method stub
if (session != null && session.isOpened()) {
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) {
if (delegate!=null)
delegate.onCompletedProgress(user, response);
// Toast.makeText(activity, "Sharing to Facebook", Toast.LENGTH_LONG).show();
// publishFeedDialog(activity, fl);
publishFeedDialog();
}
}
}).executeAsync();
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
//
public void setDelegate(FacebookloginDelegate delegate_)
{
delegate = delegate_;
}
protected boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
public static abstract class FacebookloginDelegate {
protected void onCompletedProgress(GraphUser user,
Response response) {}
}
public void publishFeedDialog()
{
Session session = Session.getActiveSession();
//if session is not empty and it is opened
if (session != null && session.isOpened()){
postOnWall();
}
else
{
// login with facebook if no session is available
loginWithFacebook();
}
}
public void postOnWall() {
Bundle params = new Bundle();
params.putString("caption", "My Caption");
params.putString("description", "description here");
params.putString("picture", "http://test.com");
params.putString("name", "name string");
params.putString("message", "my message here");
session = Session.getActiveSession();
if(session != null && session.isOpened()){
// Check for publish permissions
if(!session.getPermissions().contains("publish_actions")) {
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSIONS));
Log.d("FBAUTOPOST","FBAUTOPOST");
}
Request postToWall = new Request(session,"me/feed", params, HttpMethod.POST, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// TODO Auto-generated method stub
Log.i("FB AutoPost:", "FBAUTOPOST" + response.toString());
Toast.makeText(main.this, "Content post successfully ", Toast.LENGTH_LONG).show();
//session.close();
}
});
RequestAsyncTask task = new RequestAsyncTask(postToWall);
task.execute();
}
}
Error msg :
07-26 18:42:02.705: I/FB AutoPost:(4348): FBAUTOPOST{Response: responseCode: 403, graphObject: null, error: {HttpStatus: 403, errorCode: 200, errorType: OAuthException, errorMessage: (#200) The user hasn't authorized the application to perform this action}, isFromCache:false}
This error code appear after post response from facebook. I have added in app_id in my string.xml. Thanks in advanced.
Most permissions need to get approved by Facebook before you can use them for Users. Without approval, those permissions only work for App Admins. Check out the changelog: https://developers.facebook.com/docs/apps/changelog
Apps requesting more than public_profile, email and the user_friends permission must be reviewed by Facebook before those permissions can be requested from people
Review Guidelines: https://developers.facebook.com/docs/apps/review

Permission facebook sdk Android

Working on Facebook. Unable to get publish_actions permission. Using this code:
session.requestNewPublishPermissions(new
Session.NewPermissionsRequest(this, PERMISSION));
any solution...
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private boolean pendingPublishReauthorization = false;
in onActivityResult do this
Session session = Session.getActiveSession();
if (session != null) {
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermsnRequest = new Session.NewPermissionsRequest(
this, PERMISSIONS);
session.requestNewPublishPermissions(newPermsnRequest );
return;
}
}
Also implement this in your class.
private boolean isSubsetOf(Collection<String> a,
Collection<String> b) {
for (String string : a) {
if (!b.contains(string)) {
return false;
}
}
return true;
}
By doing this you will be able to get all the public permissions. you have to open the session after getting read permissions and then only request for publish permissions.
Facebook sdk only returns read-permission, but not the write permissions. You can user the "/me" endpoint to get all the permissions.
final Bundle permBundle = new Bundle();
permBundle.putCharSequence("permission", "publish_actions");
GraphRequest request = new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me/permissions", permBundle, HttpMethod.GET,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
Log.d(TAG, "response2: " + graphResponse.getJSONObject());
try {
JSONArray permList = (JSONArray) graphResponse.getJSONObject().get("data");
if(permList.length() == 0){
// no data for perms, hence asking permission
askForFBPublishPerm();
}else{
JSONObject permData = (JSONObject) permList.get(0);
String permVal = (String) permData.get("status");
if(permVal.equals("granted")){
postToFB();
}else{
askForFBPublishPerm();
}
}
} catch (JSONException e) {
Log.d(TAG, "exception while parsing fb check perm data" + e.toString());
}
}
}
);
request.executeAsync();

Post on FB wall Using 3.0 SDK

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() {
}
});
}

Android Facebook native app not getting user email and birthday even with permissions set and correct information in fields

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();
}
}

Categories

Resources