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.
Related
I am trying to do a facebook login in my application but i am not able to send the value of facebook email to the app server. when i am debugging the app inside onCompleted i can see the facebook email but when i am passing that value it shows null.fb_login is an ImageButton, its not a facebooklogin button.
here is my Code :-
fb_login.setOnClickListener(v -> {
if (internetDetector.hasConnectivity()) {
flag = 1;
onFblogin();
}
else {
Toast.makeText(LoginActivity.this,"Please Check Your Internet Connection",Toast.LENGTH_LONG).show();
}
});
Below is onfbLogin method in which i am making a graph request and trying to save the email , id , name into the variables which are global.
private void onFblogin() {
callbackManager = CallbackManager.Factory.create();
// Set permissions
fbLoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList( "email", "public_profile"));
fbLoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("Success");
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json, GraphResponse response) {
if (response.getError() != null) {
// handle error
System.out.println("ERROR");
} else {
System.out.println("Success");
try {
String jsonresult = String.valueOf(json);
System.out.println("JSON Result"+jsonresult);
facebookName = json.getString("name");
facebookEmail = json.getString("email");
facebookid = json.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.d("facebook Login","On cancel");
}
#Override
public void onError(FacebookException error) {
Log.d("facebook Login",error.toString());
}
});
return;
}
after this i am having onActivityResult method.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> completedTask = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(completedTask);
}
else {
callbackManager.onActivityResult(requestCode, resultCode, data);
postDataToServer();
}
}
Inside the postDataToServer() method i am trying to get the values of facebookEmail but i am getting null over there. Maybe i am doing it in a wrong manner. Please guide me so i can make changes and get the values of variables.
I am attempting to implement Facebook login into my Android app following: https://developers.facebook.com/docs/facebook-login/android
Through following their implementation, I can Facebook login steps, successfully login, but afterward, the success callback does nothing:
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.button_facebook_sign_in);
loginButton.setReadPermissions("email");
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
Toast.makeText(LoginActivity.this, loginResult.getAccessToken().toString(), Toast.LENGTH_SHORT).show();
Log.v("KJA onSuccess", "Facebook Login succeeded");
}
#Override
public void onCancel() {
// App code
Log.v("KJA onCancel", "Cancel called");
}
#Override
public void onError(FacebookException exception) {
// App code
Log.v("KJA onError", exception.toString());
}
});
How can I ensure the callback receives the notification of login success?
Before clicking Facebook, check if user is already logged in.
try {
String curr_id = Profile.getCurrentProfile().getId();
Log.w("FB_CURRENT_ID", "Current ID: " + curr_id );
} catch (Exception e) {
Log.w("FB_CURRENT_ID", "Not Logged In!");
}
Try this code for button click:
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("LoginActivity", response.toString());
if (object.has("picture")) {
try {
String profilePicUrl = object.getJSONObject("picture").getJSONObject("data").getString("url");
String nameOfUser = object.getString("name");
String id = object.getString("id");
Log.w("facebook_id", id);
Log.w("facebook_name", nameOfUser);
Log.w("facebook_pic", profilePicUrl);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
}
);
Add onActivityResult in your class. Here's the code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
I am implementing a Facebook login with the SDK 4 but it only works once.
When I install the app I can login with Facebook perfectly. However, when I logout and try to login again, I get the Sorry, something went wrong message:
How I init SDK:
// Called in onCreate()
private void initFacebook() {
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "On success");
getUserData(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "On cancel");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, error.toString());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (callbackManager != null) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
private void getUserData(AccessToken accessToken) {
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject json,
GraphResponse response) {
Log.v(TAG, response.toString());
if (response.getError() != null) {
// handle error
Log.d(TAG, "GraphRequest error");
} else {
Log.d(TAG, "GraphRequest success");
try {
String jsonresult = String.valueOf(json);
Log.d(TAG, "JSON Result" + jsonresult);
String str_email = json.getString("email");
String str_id = json.getString("id");
String str_name = json.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
onLoginSuccess();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email");
request.setParameters(parameters);
request.executeAsync();
}
And here the login and logout:
#Override
public void onLoginClicked() {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email"));
}
#Override
public void onLogoutClicked() {
LoginManager.getInstance().logOut();
}
What is going wrong?
Thanks!
first of all initialize facebook sdk , just before setContentview();
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.main);
then in onResume() you should call
#Override
protected void onResume() {
super.onResume();
AppEventsLogger.activateApp(this);
}
in onPause() call following:
#Override
public void onPause() {
super.onPause();
//for facebook
AppEventsLogger.deactivateApp(this);
}
except this your code is looking fine, yesterday i also got some problem like this, i guess it is problem from Facebook, because today my app work fine automatically.
Getting mad with this. I try to login into FB and at the same time retrieve user information.
The FB login works fine, the app changes to FB, shows what permission the app is asking for and after pressing Accept, goes back to my app. BUT the registerCallback is never called. Where is my mistake? here my code:
FacebookSdk.sdkInitialize(getApplicationContext());
CallbackManager mCallbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().logInWithReadPermissions(
this,
permissionNeeds);
LoginManager.getInstance().registerCallback(mCallbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.e("dd", "SUCCESS");
GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json, GraphResponse response) {
if (response.getError() != null) {
System.out.println("ERROR");
} else {
System.out.println("Success");
try {
String jsonresult = String.valueOf(json);
System.out.println("JSON Result" + jsonresult);
String str_email = json.getString("email");
String str_id = json.getString("id");
String str_firstname = json.getString("first_name");
String str_lastname = json.getString("last_name");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}).executeAsync();
}
#Override
public void onCancel() {
Log.e("dd", "facebook login canceled");
}
#Override
public void onError(FacebookException e) {
Log.e("dd", "facebook login failed error");
}
});
EDIT:
found it, the following code was missing, now I am getting the user information after login
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
Am working for facebook public page post. My Customers will login with facebook (inside my application) to link their public pages to my application. With this login is it possible to get customers public pages list created by them in facebook?
As of now i can able to get the user details but not the pages AND events.
Here is my answer to my own question after a long research its worked fine with public pages as response from activity result.
public class AdminFbLogin extends Activity {
private ProgressDialog pDialog;
private String userName ="", accessToken = "";
private JSONArray fbPages = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebookLogout();
pDialog = new ProgressDialog(this);
pDialog.setMessage("loading");
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setCanceledOnTouchOutside(false);
try{
Session.openActiveSession(AdminFbLogin.this, true, new Session.StatusCallback() {
// callback when session changes state
#SuppressWarnings("deprecation")
#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) {
userName = user.getName();
if(fbPages != null ) {
returnAccessToken();
}
}
}
});
}
}
});
} catch(Exception e){
Toast.makeText(AdminFbLogin.this, "Please check your internet connection. ", Toast.LENGTH_LONG).show();
pDialog.dismiss();
Log.e("AdminFBLogin Error",e.getLocalizedMessage(),e);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
accessToken = Session.getActiveSession().getAccessToken();
final Session session = Session.getActiveSession();
if (session.isOpened()) {
new Request(session, "/me/accounts", null, HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
try{
GraphObject go = response.getGraphObject();
fbPages = (JSONArray) go.getProperty("data");
Log.d("User Response :", response.toString());
if(!userName.equals("")) {
returnAccessToken();
}
} catch(Exception e){
Log.e("JSOn Exception", e.getLocalizedMessage(),e);
}
}
}
).executeAsync();
}
}
private void returnAccessToken(){
Intent data = new Intent();
data.putExtra("accessToken", accessToken);
data.putExtra("fbPages", fbPages.toString());
data.putExtra("userName", userName);
setResult(RESULT_OK, data);
facebookLogout();
finish();
}
}
You should probably have a look at the SDK and the tutorials:
https://developers.facebook.com/docs/android/sample-apps