i am getting a null when i try to fetch my friend's birthday . this is where i set the permissions
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.activity_main, container, false);
LoginButton authButton = (LoginButton) view
.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("user_likes",
"friends_birthday", "friends_about_me"));
return view;
// return super.onCreateView(inflater, container, savedInstanceState);
}
and this is how i am trying to fetch birthdays
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
Request.executeMyFriendsRequestAsync(session,
new Request.GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users,
Response response) {
// TODO Auto-generated method stub
// Log.i("Response JSON", response.toString());
names = new String[users.size()];
id = new String[users.size()];
for (int i = 0; i < users.size(); i++) {
names[i] = users.get(i).getBirthday();
//id[i] = users.get(i).ge();
Log.i("Birthday chakk te bai ", "Birthday"
+ names[i]);
}
}
});
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
Please see why i am geeting null . Every thing is fine with keyhash as i tested it for friends name .
App is only in the sandbox mode.
Try this-
Your callback, where you'll get friends and birthday info(if authenticated):
Session.StatusCallback statusCallback = new Session.StatusCallback()
{
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception)
{
if (session.isOpened())
{
getFriendDetails();
}
}
};
Then, open the session and set the permissions:
Session session = new Session(this);
session.openForRead(new Session.OpenRequest(this)
.setCallback(statusCallback)
.setPermissions(Arrays.asList("friends_birthday")));
As a last step, get the friends birthday and other details:
private void getFriendDetails()
{
Request myFriendsRequest = Request.newMyFriendsRequest(Session.getActiveSession(),
new Request.GraphUserListCallback()
{
#Override
public void onCompleted(List<GraphUser> users, Response response)
{
if (response.getError() == null)
{
// Print response
}
}
});
Bundle requestParams = myFriendsRequest.getParameters();
requestParams.putString("fields", "name,birthday");
myFriendsRequest.setParameters(requestParams);
myFriendsRequest.executeAsync();
}
Related
for my android application i wanted to integrate a facebook login, so i did exactly what is here:
https://github.com/ParsePlatform/IntegratingFacebookTutorial
Everything seems to work fine however the values which are stored in the parse backend are not convenient, here is for example what i get after login with my facebook account:
emailVerified:empty
username:adGdJMxcCQCAo2.....
authData: {"facebook":{"access_token":"CAAMBDxU3HgUBAMYQ8q2mnjDqeKBz2sw......","expiration_date":"...","id":"1015353..."}}
Sorry i still can't upload pictures..
Is this normal?
i'm using parseFacebookUtils 1.9.4
parse 1.9.4
This is what i had done for facebook parse.com login
LoginFragment.java
private ParseLoginConfig config;
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState, 1);
rootView = inflater.inflate(R.layout.layout_login, container, false);
config = ParseLoginConfig.fromBundle(getArguments(), getActivity());
return rootView;
}
private void loginUsingFacebook() {
// TODO Auto-generated method stub
if (config.isFacebookLoginNeedPublishPermissions()) {
ParseFacebookUtils.logInWithPublishPermissionsInBackground(
getActivity(), Arrays.asList("public_profile", "email"),
facebookLoginCallbackV4);
} else {
ParseFacebookUtils.logInWithReadPermissionsInBackground(
getActivity(), Arrays.asList("public_profile", "email"),
facebookLoginCallbackV4);
}
}
private LogInCallback facebookLoginCallbackV4 = new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e) {
if (isActivityDestroyed()) {
return;
}
if (user == null) {
loadingFinish();
if (e != null) {
showToast(R.string.com_parse_ui_facebook_login_failed_toast);
debugLog(getString(R.string.com_parse_ui_login_warning_facebook_login_failed)
+ e.toString());
}
} else if (user.isNew()) {
GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject fbUser,
GraphResponse response) {
/*
* If we were able to successfully retrieve the
* Facebook user's name, let's set it on the
* fullName field.
*/
Log.e("facebook User", fbUser.toString());
final ParseUser parseUser = ParseUser
.getCurrentUser();
if (fbUser != null
&& parseUser != null
&& fbUser.optString("name").length() > 0) {
parseUser.put(USER_OBJECT_NAME_FIELD,
fbUser.optString("name"));
parseUser.put(USER_OBJECT_EMAIL_FIELD,
fbUser.optString("email"));
parseUser
.saveInBackground(new SaveCallback() {
#Override
public void done(
ParseException e) {
if (e != null) {
debugLog(getString(R.string.com_parse_ui_login_warning_facebook_login_user_update_failed)
+ e.toString());
}
ParseInstallation installation = ParseInstallation
.getCurrentInstallation();
installation
.put(BaseFragment.INSTALLATION_UNIQUE_ID,
parseUser
.getUsername());
installation
.saveInBackground();
loginSuccess();
}
});
}
}
}).executeAsync();
}
}
};
Note : Remove toast messages and and text me if any query!!
When I wrote the following code for API V2.3 this was giving me all details including email id. And now the same code is not giving me email id. What can I can do to get email id?
oncreate(..)
{
.
.
EMAIL_PERMISSION = new ArrayList<String>();
EMAIL_PERMISSION.add("email");
uiLifecycleHelper = new UiLifecycleHelper(this, statusCallback);
uiLifecycleHelper.onCreate(savedInstanceState);
Session.openActiveSession(this, true, EMAIL_PERMISSION,
statusCallback);
// callback when session changes state
Session.StatusCallback statusCallback = new StatusCallback()
{
#Override
public void call(Session session, SessionState state, Exception
exception)
{
// Checking whether the session is opened or not
if (state.isOpened())
{
} else
{
if (state.isClosed())
{
}
Log.d(TAG, state.toString());
}
}
};
// Method to get user facebook profile
void getUserFacebookProfile(Session session, final boolean finish)
{
// Checking whether the session is opened or not
if (session.isOpened())
{
// Sending request to the facebook to get user facebook profile
Request.newMeRequest(session, new GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
if (user != null)
{
// To get network user id
String networkUserid = user.getId();
// To get user first name
String fname = user.getFirstName();
// To get user last name
String lname = user.getLastName();
// To get user middle name
String mname = user.getMiddleName();
// String email = user.getProperty("email").toString();
String email = response.getGraphObject().getProperty("email")
.toString();
}
Now the above code gave me all details including email id for V2.3, now i'm not able to get email id. Please let me know solution. Thanks.
public class LoginFacebook {
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
public void openFB() {
LoginManager.getInstance().logInWithReadPermissions(activity,
Arrays.asList("read_stream", "user_photos", "email", "user_location"));
// Login Callback registration
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
new GraphRequest(AccessToken.getCurrentAccessToken(),
"/me", null, HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(
GraphResponse response) {
/* handle the result */
try {
//GET USER INFORMATION
JSONObject json = response.getJSONObject();
String email = json.getString("email");
String fullName = json.getString("name");
String accessToken = loginResult.getAccessToken().getToken();
int type = 1;
String lastUpdate = json.getString("updated_time");
String user_id = json.getString("id");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAsync();
GetSnsPost getSnsPost = GetSnsPost.getInstance(activity);
getSnsPost.getFacebookPosts();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});
}
public void loginFacebook(View v){
openFB();
}
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
Since session have been deprecated long time ago, I don't use it anymore. I get user information this way. Hope this code will solve your problem ;)
Bundle params = new Bundle();
params.putString("fields", "id,name,email,birthday,first_name,last_name");
new GraphRequest(
AccessToken.getCurrentAccessToken(),
AccessToken.getCurrentAccessToken().getUserId(),
params, HttpMethod.GET,
new GraphRequest.Callback() {
#Override
public void onCompleted(
GraphResponse response) {
System.out.println("\n J S O N :"
+ response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAsync();
i'm trying to get the user details on facebook android sdk..
i'm not getting results from Request.newMeRequest(session, new Request.GraphUserCallback() which is an updated function from android sdk manager
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
private TextView userInfoTextView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, container, false);
LoginButton authButton = (LoginButton) view
.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("user_location",
"user_birthday", "user_likes"));
userInfoTextView = (TextView) view.findViewById(R.id.userInfoTextView);
return view;
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
userInfoTextView.setVisibility(View.VISIBLE);
Settings.addLoggingBehavior(LoggingBehavior.REQUESTS);
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generatedation I put the tags below in wrong
// places (I method stub
if (user != null) {
// Display the parsed user info
Toast.makeText(null, "Entered the user section",
Toast.LENGTH_LONG).show();
userInfoTextView.setText(buildUserInfoDisplay(user));
} else if (user == null) {
Toast.makeText(null, "User is null error in request",
Toast.LENGTH_LONG).show();
}
}
}).executeAsync();
Log.i(TAG, "Logged in...");
} else if (state.isClosed()) {
userInfoTextView.setVisibility(View.INVISIBLE);
Log.i(TAG, "Logged out...");
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
private String buildUserInfoDisplay(GraphUser user) {
StringBuilder userInfo = new StringBuilder("");
userInfo.append(String.format("Name: %s\n\n", user.getName()));
userInfo.append(String.format("Birthday: %s\n\n", user.getBirthday()));
userInfo.append(String.format("Location: %s\n\n", user.getLocation()
.getProperty("name")));
userInfo.append(String.format("Locale: %s\n\n",
user.getProperty("locale")));
// JSONArray languages = (JSONArray)user.getProperty("languages");
GraphObjectList<MyGraphLanguage> languages = (user
.cast(MyGraphUser.class)).getLanguages();
if (languages.size() > 0) {
ArrayList<String> languageNames = new ArrayList<String>();
for (MyGraphLanguage language : languages) {
languageNames.add(language.getName());
}
userInfo.append(String.format("Languages: %s\n\n",
languageNames.toString()));
}
return userInfo.toString();
}
private interface MyGraphLanguage extends GraphObject {
// Getter for the ID field
String getId();
// Getter for the Name field
String getName();
}
private interface MyGraphUser extends GraphUser {
// Create a setter to enable easy extraction of the languages field
GraphObjectList<MyGraphLanguage> getLanguages();
}
}
You can try with simple following code.
public class Profile_Detail extends Activity implements OnClickListener {
ImageView profile_pic;
TextView mfirstname, mlastname, mfullname, mfacebookLink, mfacebookId,
mfacebookUnm, mgender, mEmail;
private Session.StatusCallback statusCallback = new SessionStatusCallback();
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
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.openForRead(new Session.OpenRequest(this)
.setCallback(statusCallback));
}
}
profile_pic = (ImageView) findViewById(R.id.profile_pic);
mfirstname = (TextView) findViewById(R.id.textView1);
mlastname = (TextView) findViewById(R.id.textView2);
mfullname = (TextView) findViewById(R.id.textView3);
mfacebookLink = (TextView) findViewById(R.id.textView4);
mfacebookId = (TextView) findViewById(R.id.textView5);
mfacebookUnm = (TextView) findViewById(R.id.textView6);
mgender = (TextView) findViewById(R.id.textView7);
mEmail = (TextView) findViewById(R.id.textView8);
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) {
mfirstname.setText(user.getFirstName());
mlastname.setText(user.getLastName());
mfullname.setText(user.getName());
mfacebookLink.setText(user.getLink());
mfacebookId.setText(user.getId());
mfacebookUnm.setText(user.getUsername()
+ " (" + user.getName() + ")");
String gender = user.asMap()
.get("gender").toString();
String email = user.asMap()
.get("email").toString();
mgender.setText(gender);
mEmail.setText(email);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL image_value = new URL(
"http://graph.facebook.com/"
+ user.getId()
+ "/picture?type=large");
Bitmap bmp = null;
try {
bmp = BitmapFactory
.decodeStream(image_value
.openConnection()
.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
profile_pic.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
});
} else {
Toast.makeText(getApplicationContext(), "Error...",
Toast.LENGTH_LONG);
}
}
});
}
#Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}
#Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state,
Exception exception) {
}
}
}
With this above code i am successfully able to get the detail of facebook user as well as profile picture.
I'm a newbie to facebook sdk development on android and, I'm making a Graph API query to retrieve FriendList information from my facebook profile.
I'm using the latest sdk. There are solutions on SOF w.r.t old sdk but I want to implement it using the latest kit.
The query to /me/friends return a JSON response with the name and IDs of friends which I was easily able to parse. But when I tried to get extra information like birthdays by querying /me/friends/?fields=birthday, I'm getting an invalid response.
I have set the permissions for friends_birthday also in the onCreateView method below.
Here is my code:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("user_location", "user_birthday", "user_likes","read_friendlists","friends_birthday")); /*setting permissions*/
userInfoTextView = (TextView) view.findViewById(R.id.userInfoTextView);
return view;
}
public void onResume() {
super.onResume();
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
userInfoTextView.setVisibility(View.VISIBLE);
Settings.addLoggingBehavior(LoggingBehavior.REQUESTS);
String graphpath="/me/friends?fields=name,birthday";
Request.executeGraphPathRequestAsync(session, graphpath, new Request.Callback(){
#Override
public void onCompleted(Response response) {
try {
userInfoTextView.setText(buildUserInfoDisplay(response));
} catch (JSONException e) {
Log.d(TAG,"JSON exception");
e.printStackTrace();
}
}
});
}
else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
userInfoTextView.setVisibility(View.INVISIBLE);
}
}
private String buildUserInfoDisplay(Response response) throws JSONException {
if(response.getError()!=null)
Log.d(TAG, "null reponse returned...");
GraphObject go = response.getGraphObject();
JSONObject jso = go.getInnerJSONObject();
JSONArray arr = jso.getJSONArray( "data" );
JSONObject json_obj = arr.getJSONObject(2); /*getting the third friend from the list*/
String birthday = json_obj.getString( "birthday");
return birthday;
}
Not all friends have birthday entries. So you will need to check if there is a 'birthday' tag available before reading it directly. You can test the result in Graph Explorer
https://developers.facebook.com/tools/explorer?method=GET&path=me%2Ffriends%3Ffields%3Dname%2Cid%2Cbirthday
I'm trying to give users an option to set/revoke publishing permission via checkbox (Facebook SDK for Android). Code is provided below. Everything works fine except that after revoking the code responsible for checking publishing permissions fails miserably.
I understand that Session has no way of knowing if user has revoked any permissions after loggin in. What is the correct way to handle this kind of situation? Do I have to query available permissions manually, or is there a way to seamlessly recreate session with basic permissions?
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
publishCheckbox = (CheckBox) view.findViewById(R.id.publishCheckbox);
publishCheckbox.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
CheckBox chb = (CheckBox) v;
if (chb.isChecked() && checkForPublishPermission() == false){
requestPublishPermissions();
}
else{
removePublishPermissions();
}
}
});
...
}
private void requestPublishPermissions() {
Session session = Session.getActiveSession();
if ( session!= null && session.isOpened()){
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, PERMISSIONS).setRequestCode(REAUTH_ACTIVITY_CODE);
newPermissionsRequest.setCallback(callback);
session.requestNewPublishPermissions(newPermissionsRequest);
}
}
private void removePublishPermissions() {
Request r = new Request(Session.getActiveSession(), PUBLISH_ACTIONS_PERMISSION_PATH, null, HttpMethod.DELETE);
r.setCallback(new Request.Callback() {
#Override
public void onCompleted(Response response) {
publishCheckbox.setEnabled(true);
}
});
r.executeAsync();
publishCheckbox.setEnabled(false);
}
private boolean checkForPublishPermission(){
boolean result = false;
Session session = Session.getActiveSession();
if (session == null || !session.isOpened()) {
result = false;
}
else{
List<String> permissions = session.getPermissions();
if (permissions.containsAll(PERMISSIONS)) {
result = true;
}
}
return(result);
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
...
publishCheckbox.setChecked(checkForPublishPermission());
...
} else if (state.isClosed()) {
...
}
}
Well I ended up requesting user permissions each time I needed such a check, something along these lines:
private void checkForPublishPermission(){
mPublishCheckbox.setEnabled(false);
Request r = new Request(Session.getActiveSession(), PUBLISH_ACTIONS_PERMISSION_PATH, null, HttpMethod.GET);
r.setCallback(new Request.Callback() {
#Override
public void onCompleted(Response response) {
if (response != null) {
GraphObject o = response.getGraphObject();
if ( o != null){
JSONArray data = o.getInnerJSONObject().optJSONArray("data");
mCanPublish = (data.optJSONObject(0).has("publish_actions"))?true:false;
mPublishCheckbox.setChecked(mCanPublish);
}
}
mPublishCheckbox.setEnabled(true);
}
});
r.executeAsync();
}