Android-simple-facebook lib, get user birthday date - android

The question in github
I'm using android-simple-facebook lib to make login in facebook and get some user data.
In this case the problem that I'm facing is that I can't get the user's birthdate data.
I've set the permissions to the SimpleFacebookConfiguration object
private Permission[] permissions = new Permission[]{
Permission.EMAIL,
Permission.USER_BIRTHDAY,
Permission.PUBLIC_PROFILE,
Permission.PUBLISH_ACTION
};
and this profile's permissions to get the data
Profile.Properties properties = new Profile.Properties.Builder()
.add(Profile.Properties.ID)
.add(Profile.Properties.FIRST_NAME)
.add(Profile.Properties.LAST_NAME)
.add(Profile.Properties.BIRTHDAY)
.add(Profile.Properties.AGE_RANGE)
.add(Profile.Properties.EMAIL)
.add(Profile.Properties.GENDER)
.build();
But I can't get the data from any of them. Any idea?

To request for new permission
private Permission[] permissions = new Permission[]{
Permission.EMAIL,
Permission.USER_BIRTHDAY,
};
SimpleFacebook.getInstance().requestNewPermissions(permissions, new OnNewPermissionsListener() {
#Override
public void onFail(String reason) {
//mResult.setText(reason);
System.out.println(""+reason);
}
#Override
public void onException(Throwable throwable) {
// mResult.setText(throwable.getMessage());
System.out.println(""+throwable.getMessage());
}
#Override
public void onCancel() {
}
#Override
public void onSuccess(String accessToken, List<Permission> acceptedPermissions, List<Permission> declinedPermissions) {
// showGrantedPermissions();
mSimpleFacebook.getProfile(properties, onProfileListener);
if (declinedPermissions != null && declinedPermissions.size() > 0) {
Toast.makeText(LoginActivity.this, "User declined few permissions: " + declinedPermissions.toString(), Toast.LENGTH_SHORT).show();
}
}
});
Profile.Properties properties = new Profile.Properties.Builder()
.add(Profile.Properties.ID)
.add(Profile.Properties.FIRST_NAME)
.add(Profile.Properties.LAST_NAME)
.add(Profile.Properties.BIRTHDAY)
.add(Profile.Properties.AGE_RANGE)
.add(Profile.Properties.EMAIL)
.add(Profile.Properties.GENDER)
.build();

Related

Invalid OAuth2 Credentials in Uber SDK for android

Below is my code to retrieve user profile. My login is successful , but when I try to fetch email address, I get the above error:
private void initializeUber(){
if(!UberSdk.isInitialized()) {
SessionConfiguration config = new SessionConfiguration.Builder()
// mandatory
.setClientId(AppConstants.UBER_CLIENT_ID)
// required for enhanced button features
.setServerToken(AppConstants.UBER_SERVER_TOKEN)
// required scope for Ride Request Widget features
.setScopes(Arrays.asList(Scope.PROFILE))
// optional: set Sandbox as operating environment
.setEnvironment(SessionConfiguration.Environment.SANDBOX)
.build();
UberSdk.initialize(config);
}
}
private void checkLoginForUber() {
LoginCallback loginCallback = new LoginCallback() {
#Override
public void onLoginCancel() {
// User canceled login
Log.i(TAG, "login cancelled");
}
#Override
public void onLoginError(#NonNull AuthenticationError error) {
// Error occurred during login
Log.i(TAG, error.toString());
Log.i(TAG, "login failed");
}
#Override
public void onLoginSuccess(#NonNull AccessToken accessToken) {
// Successful login! The AccessToken will have already been saved.
Log.i(TAG, "login successful");
getUserProfile();
}
#Override
public void onAuthorizationCodeReceived(#NonNull String authorizationCode) {
Log.i(TAG, authorizationCode);
}
};
accessTokenManager = new AccessTokenManager(this);
loginManager = new LoginManager(accessTokenManager, loginCallback);
loginManager.login(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
loginManager.onActivityResult(this, requestCode, resultCode, data);
}
private void getUserProfile(){
try {
AccessToken accessToken = accessTokenManager.getAccessToken();
Log.i(TAG,accessToken.getToken());
Session session = loginManager.getSession();
AppContext.getmInstance().setSession(session);
//Intent intent = new Intent(this, UbserService.class);
//startService(intent);
RidesService service = UberRidesApi.with(session).build().createService();
service.getUserProfile().enqueue(new Callback<UserProfile>() {
#Override
public void onResponse(Call<UserProfile> call, Response<UserProfile> response) {
Log.i(TAG, response.toString());
if (response.isSuccessful()) {
//Success
UserProfile profile = response.body();
Log.i(TAG,profile.getEmail());
} else {
//Api Failure
ApiError error = ErrorParser.parseError(response);
for (int i = 0; i < error.getClientErrors().size(); i++) {
Log.i(TAG, error.getClientErrors().get(i).getTitle());
}
}
}
#Override
public void onFailure(Call<UserProfile> call, Throwable t) {
//Network Failure
}
});
}catch (Exception ex){
ex.printStackTrace();
}
}
What I am doing here? The app redirects to Uber app, where I grant access to fetch user info. After I am back to my app, the login successful is called, but as I call getUserProfile, I get this error. I am using SSO for authentication.

"CONNECTIVITY_ISSUE" error while using android-uber-sdk

I am receiving an authentication error "CONNECTIVITY_ISSUE" when I try to login using android sdk LoginManager in sandbox mode.
SessionConfiguration config = new SessionConfiguration.Builder()
.setClientId(Constants.UBER_CLIENTID)
.setEnvironment(SessionConfiguration.Environment.SANDBOX)
.setScopes(Arrays.asList(Scope.PROFILE, Scope.RIDE_WIDGETS,Scope.REQUEST))
.build();
UberSdk.initialize(config);
accessTokenManager = new AccessTokenManager(this);
LoginCallback loginCallback = new LoginCallback() {
#Override
public void onLoginCancel() {
}
#Override
public void onLoginError(#NonNull AuthenticationError error) {
}
#Override
public void onLoginSuccess(#NonNull AccessToken accessToken) {
}
#Override
public void onAuthorizationCodeReceived(#NonNull String authorizationCode) {
authorizationCode=authorizationCode;
}
};
loginManager = new LoginManager(accessTokenManager, loginCallback);
if (accessTokenManager.getAccessToken() == null) {
loginManager.setRedirectForAuthorizationCode(true);
loginManager.login(this);
}
I have followed uber developer documentation and I am not able to solve this error. Can anyone help me on this?
Looks like you are missing the redirect uri from your SessionConfiguration, try adding it in like this:
.setRedirectUri("YOUR_REDIRECT_URI").
More information in the readme

Unable to get Publish Permission With Test User Facebook Android

I want to publish post to user's wall. I know Facebook only allows tester and developers to post on wall. I have already added user to tester list. When I try to get publish permission, it says that user has already granted permission (as shown in screenshot) and returns. I am not able to get permission or post on wall. Moreover, callback's any method is not called as well.
CODE
I have followed code from Facebook Example RPSSample.
//Publish to wall
public void publishResult() {
registerPublishPermissionCallback();
if (canPublish()) { //see definition below
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse(urlToPost))
.build();
ShareApi.share(content, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
callback.didShareOnFacebookSuccessfully();
}
#Override
public void onCancel() {
// This should not happen
}
#Override
public void onError(FacebookException error) {
showToast(error.getMessage());
}
});
}
}
//check if user has permission or not
private boolean canPublish() {
final AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null) {
if (accessToken.getPermissions().contains(AppConstants.ADDITIONAL_PERMISSIONS)) {
// if we already have publish permissions, then go ahead and publish
return true;
} else {
// otherwise we ask the user if they'd like to publish to facebook
new AlertDialog.Builder(activity)
.setTitle(R.string.share_with_friends_title)
.setMessage(urlToPost)
.setPositiveButton(R.string.share_with_friends_yes, canPublishClickListener)
.setNegativeButton(R.string.share_with_friends_no, dontPublishClickListener)
.show();
return false;
}
}
return false;
}
//If user allows, ask Facebook to grant publish_action permission
private DialogInterface.OnClickListener canPublishClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (AccessToken.getCurrentAccessToken() != null) {
// if they choose to publish, then we request for publish permissions
LoginManager.getInstance()
.setDefaultAudience(DefaultAudience.FRIENDS)
.logInWithPublishPermissions(activity,
Arrays.asList(AppConstants.ADDITIONAL_PERMISSIONS));
}
}
};
//Callback - Any of the method doesn't call.
private void registerPublishPermissionCallback() {
LoginManager.getInstance().registerCallback(
callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken.getPermissions().contains(AppConstants.ADDITIONAL_PERMISSIONS)) {
publishResult();
} else {
handleError("Not enough permissions to publish");
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
handleError(exception.getMessage());
}
private void handleError(String errorMessage) {
// this means the user did not grant us write permissions, so
// we don't do implicit publishes
showToast(errorMessage);
}
}
);
}
My app is live on console. Please guide what is requirement of Facebook to get publish permission with test user? Thanks.
Use below code to check if permission is Granted or not.
String url = "/" + "(userFbID)" + "/permissions";
new GraphRequest(AccessToken.getCurrentAccessToken(), url, null,
HttpMethod.GET, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
try {
JSONObject json = new JSONObject(
response.getRawResponse());
JSONArray data = json.getJSONArray("data");
boolean isPermitted = false;
for (int i = 0; i < data.length(); i++) {
if (data.getJSONObject(i)
.getString("permission")
.equals("publish_actions")) {
isPermitted = true;
String status = data.getJSONObject(i)
.getString("status");
if (status.equals("granted")) {
publishResult()
} else {
LoginFacebook();
}
break;
}
}
if (!isPermitted) {
LoginFacebook();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).executeAsync();
replace user's fb id on place of (userFbID).
If permission is not granted then use this function to ask user for that permission.
private void LoginFacebook() {
loginManager = LoginManager.getInstance();
loginManager.logInWithPublishPermissions(this,
Arrays.asList("publish_actions"));
loginManager.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
publishResult()
}
#Override
public void onError(FacebookException error) {
}
#Override
public void onCancel() {
}
});
}
Finally able to solve the problem. There was no issue in code. It was some setting / permission issue with Facebook app. These are steps I followed:
Remove the user from Test role section in your Facebook Developer Console.
Revoke App's Access by logging into that user's account. Go to Settings > Apps. Remove the app from there. You need to wait 10-15 min, since it takes time from Facebook side to revoke access completely.
Make your Facebook App in Sandbox mode (you need to do this to perform publish testing).
Login your android app using any Facebook account other than app admin. It should throw error that app is in development mode.
Add user as Tester in the Facebook Console App. That user may need to approve pending request at his side.
Login from that user account. Facebook will now ask you to provide basic information access to the app. After that you can test publishing. You will be able to post on the user's wall successfully.
Hope this helps someone!

Get Twitter user email using Fabric SDK

I'm logging in with twitter using Fabric.
This is how I fetch the user data:
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
AccountService ac = Twitter.getApiClient(result.data).getAccountService();
ac.verifyCredentials(true, true, new Callback<com.twitter.sdk.android.core.models.User>() {
#Override
public void success(Result<com.twitter.sdk.android.core.models.User> result) {
String imageUrl = result.data.profileImageUrl;
String email = result.data.email;
String userName = result.data.name;
System.out.println(imageUrl);
System.out.println(email);
System.out.println(userName);
}
#Override
public void failure(TwitterException e) {
}
});
}
This is working fine, except that the email variable is null when I print to log. Is there an other way of fetching the user email?
-Here is the Solution!
twitauthobj.requestEmail(twitsessionobj,new Callback<String>() {
#Override
public void success(Result<String> stringResult) {
'You code here'
}
#Override
public void failure(TwitterException e) {
}
});
-Thanks let me inform if t doesnt work!
To bypass Twitter's useless request email activity and to fix a leak, I dug through the source code and pulled this out:
new Retrofit.Builder()
.client(getClient(sessionResult))
.baseUrl(new TwitterApi().getBaseHostUrl())
.addConverterFactory(getFactory())
.build()
.create(EmailService.class)
.getEmail()
.enqueue(new Callback<User>() {
#Override
public void success(Result<User> result) {
String email = result.data.email;
// Handle the result
if (email == null) {
TwitterProvider.this.failure(
new TwitterException("Your application may not have access to"
+ " email addresses or the user may not have an email address. To request"
+ " access, please visit https://support.twitter.com/forms/platform."));
} else if (email.equals("")) {
TwitterProvider.this.failure(
new TwitterException("This user does not have an email address."));
} else {
mCallbackObject.onSuccess(createIdpResponse(sessionResult.data, email));
}
}
#Override
public void failure(TwitterException exception) {
TwitterProvider.this.failure(exception);
}
});
private OkHttpClient getClient(Result<TwitterSession> sessionResult) {
return OkHttpClientHelper.getOkHttpClient(
sessionResult.data,
TwitterCore.getInstance().getAuthConfig(),
TwitterCore.getInstance().getSSLSocketFactory());
}
private GsonConverterFactory getFactory() {
return GsonConverterFactory.create(
new GsonBuilder()
.registerTypeAdapterFactory(new SafeListAdapter())
.registerTypeAdapterFactory(new SafeMapAdapter())
.registerTypeAdapter(BindingValues.class, new BindingValuesAdapter())
.create());
}
EmailService:
interface EmailService {
#GET("/1.1/account/verify_credentials.json?include_email=true?include_entities=true?skip_status=true")
Call<User> getEmail();
}

Log in on Facebook: app is misconfigured

I try to write an application that can log in facebook. I use easyfacebooksdk.jar like library to use your API, but I have problem with configuration. I post the follow image:
This is the facebook app that I have created:
I have obtained the key hash in this way from console:
I put this code here in key has field( i can't post the image because i don't have 10 reputation)
This is my code:
public class MainActivity extends Activity implements LoginListener {
private FBLoginManager fbManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
shareFacebook();
}
public void shareFacebook() {
//change the permissions according to the function you want to use
String permissions[] = { "read_stream", "user_relationship_details",
"user_religion_politics", "user_work_history",
"user_relationships", "user_interests", "user_likes",
"user_location", "user_hometown", "user_education_history",
"user_activities", "offline_access" };
//change the parameters with those of your application
fbManager = new FBLoginManager(this, R.layout.activity_main,
"334014040053829", permissions);
if (fbManager.existsSavedFacebook()) {
fbManager.loadFacebook();
} else {
fbManager.login();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
fbManager.loginSuccess(data);
}
public void loginFail() {
fbManager.displayToast("Login failed!");
}
public void logoutSuccess() {
fbManager.displayToast("Logout success!");
}
public void loginSuccess(Facebook facebook) {
//library use example
GraphApi graphApi = new GraphApi(facebook);
User user = new User();
try {
user = graphApi.getMyAccountInfo();
graphApi.setStatus("Post by app");
} catch (EasyFacebookError e) {
e.toString();
}
}
}
I obtain this error in emulator: app is misconfigured to facebook log in but i don't understand why... Someone can you help me?

Categories

Resources