Facebook user profile image + sdk 4.0 - android

A bit puzzled with this...
I am using LoginButton class to login via facebook in my app.
I have registered a callback loginButton.registerCallback and I can get login successfully with it, this all is done in LoginActivity class of my app.
As shown below, in onSuccess method of callback, I call getFaceBookProfileDetails method, defined locally to call Graph API to fetch user details, viz name, profile picture etc, this too works well .
onSuccess(LoginResult loginResult) {
getFaceBookProfileDetails(loginResult.getAccessToken());
startActivity(intentHomeActivity)
}
Now the issue is I want to pass this facebook data to my HomeActivity where I will display this on UI.
As the graph API call runs Async on non-UI thread, I am getting Null pointer when I try to fetch this data in HomeActivity.
Looked at many work-arounds for this with no luck.
Any help would be appreciated.
facebookButton = (LoginButton) findViewById(R.id.login_button);
facebookButton.setReadPermissions(Arrays.asList("public_profile",
"email", "user_birthday"));
intentHomeActivity = new Intent(this, HomeActivity.class);
facebookButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
getFaceBookProfileDetails(loginResult.getAccessToken());
startActivity(intentHomeActivity);
}
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
private void getFaceBookProfileDetails(final AccessToken accessToken) {
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
final JSONObject object,
GraphResponse response) {
try {
Toast.makeText(getApplicationContext(), "User Name
is --"+object.get("name"), Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "User ID is
--"+object.get("id"), Toast.LENGTH_LONG).show();
ProfilePictureView profilePictureView = new
ProfilePictureView(getApplicationContext());
intentHomeActivity.putExtra(Constants.FACEBOOK_USER_OBJECT,
object.get("id").toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
request.executeAsync();

Move this line from the onSuccess() method:
startActivity(intentHomeActivity);
To the onCompleted() method. After:
intentHomeActivity.putExtra(Constants.FACEBOOK_USER_OBJECT, object.get("id").toString());
The onComplete() method would look like this:
#Override
public void onCompleted( final JSONObject object, GraphResponse response) {
try {
Toast.makeText(getApplicationContext(), "User Name is --" + object.get("name"), Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "User ID is --" + object.get("id"), Toast.LENGTH_LONG).show();
ProfilePictureView profilePictureView = new ProfilePictureView(getApplicationContext());
intentHomeActivity.putExtra(Constants.FACEBOOK_USER_OBJECT, object.get("id").toString());
startActivity(intentHomeActivity);
} catch (JSONException e) {
e.printStackTrace();
}
}

Related

Facebook auth with firebase get User data

I am trying to use Firebase authentication with Facebook.
I have successfully implemented the login part and stuck while getting the user details from facebook using accessToken.
Here is the code:
loginButton.setReadPermissions("email", "public_profile" );
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject me, GraphResponse response) {
Log.e("FBRESPONSE",me.toString());
if (response.getError() != null) {
// handle error
} else {
if (me.has("picture")) {
try {
f_photo = me.getJSONObject("picture").getJSONObject("data").getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
}
f_email = me.optString("email");
String id = me.optString("id");
f_name=me.optString("first_name")+" "+me.optString("last_name");;
handleFacebookAccessToken(loginResult.getAccessToken());
}
}
}).executeAsync();
}
});
This is the JSON response i get when called this.
E/FBRESPONSE: {"name":"Vishnu Reddy","id":"855235691328214"}
How do i get email, profile picture URL?
Please help. Thanks in advance.
You need to use the Facebook Graph API. You need to have your user signed in and call the AccessToken.refreshCurrentAccessTokenAsync(); and initiate a request to the user data-fields you need.

Facebook Android login- Passing details

Well, I want the details to be passed when moving to a next activity. Details like name, email, profile pic, gender.
This does not happen somehow when the user is logged in. However, the details are sent when I am logging in for the first time.
So I have two questions:
1) Why are the details not shown when the user is already logged in? Is there something that needs to be changed in the code?
2) Sometimes when I open the app after a long time it does not move to the DetailsActivity and opens the MainActivity with LoginButton with the text logout(so obviously it is still logged in yet returns null).
Have a look at my code:
AccessTokenTracker accessTokenTracker;
AccessToken accessToken = AccessToken.getCurrentAccessToken();
onCreate
callbackManager = CallbackManager.Factory.create();
loginButton.setReadPermissions(Arrays.asList("email, public_profile"));
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email, public_profile"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
getUserDetails(loginResult);
}
#Override
public void onCancel() {
//cancelled
}
#Override
public void onError(FacebookException exception) {
//handle error
}
});
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
accessToken = currentAccessToken;
}
};
// If already logged in show the home view
if (accessToken != null && Profile.getCurrentProfile()!=null) {
try {
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
startActivity(intent);
finish();
}
catch (RuntimeException e) {
e.printStackTrace();
}
}
else {
databaseHelper.deleteAll();
}
}
private void getUserDetails(LoginResult loginResult) {
GraphRequest data_request = GraphRequest.newMeRequest(
accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject json_object,
GraphResponse response) {
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
intent.putExtra("userProfile", json_object.toString());
startActivity(intent);
finish();
}
});
Bundle permission_param = new Bundle();
permission_param.putString("fields", "id,name,email,picture.width(120).height(120),gender");
data_request.setParameters(permission_param);
data_request.executeAsync();
}
i have done this same.I did using webservice.
Pass the user details to backend and created response as retrieving the same user details back.Then I stored the response to sharedpreference.
private void loginSuccess(JSONObject mJsonObject) {
try {
Snackbar.make(fbLoginButton, "Successfully Loged in!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
setSharedPreference(AppConstants.SharedKey.USER_ID, mJsonObject.getJSONObject(AppConstants.APIKeys.USER_DETAILS).getString(AppConstants.APIKeys.ID));
setSharedPreference(AppConstants.SharedKey.USER_NAME, mJsonObject.getJSONObject(AppConstants.APIKeys.USER_DETAILS).getString(AppConstants.APIKeys.USER_NAME));
setSharedPreference(AppConstants.SharedKey.USER_EMAIL, mJsonObject.getJSONObject(AppConstants.APIKeys.USER_DETAILS).getString(AppConstants.APIKeys.EMAIL));
setSharedPreference(AppConstants.SharedKey.LOGIN_STATUS, "true");
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
this.finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
Try this :)
In your onCompleted() do this
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
Log.e("GraphResponse", "-------------" + response.toString());
Log.e("fb_json", "-------------" + object.toString());
try {
if (object.has("id")) {
fb_id = object.getString("id");
}
if (object.has("name")) {
userName = object.getString("name");
}
if (object.has("email")) {
email = object.getString("email");
}
setSharedPreference(AppConstants.SharedKey.FB_ID, fb_id);
imageUrl = "http://graph.facebook.com/" + object.getString("id") + "/picture?type=large";
Log.e("profileImage", imageUrl);
new WebserviceCall(LoginActivity.this, AppConstants.Methods.fbLOgin).execute(new String[]{email, fb_id, userName, getSharedPreference(AppConstants.SharedKey.DEVICE_ID), "", imageUrl});
} catch (JSONException e) {
e.printStackTrace();
}
Then call webservice by passing fb_id,username,email etc and in the onPostexecute call loginSuccess(mJsonObject);

New view is not loaded when Facebook login button is clicked

I'm using Facebook Android SDK 'com.facebook.android:facebook-android-sdk:4.13.1' version.
My issue with this Facebook Version is exactly same like this question. I need to redirect to my Home screen after clicking on Facebook Login button without reverting back to Login screen. Can this SDK version(4.13.1) solve/support this feature? Please help me.
loginButton = (LoginButton) findViewById(R.id.fb_login_button);
loginButton.setReadPermissions("public_profile email");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
if (AccessToken.getCurrentAccessToken() != null) {
RequestData();
}
}
#Override
public void onCancel() {
// code for cancellation
Toast.makeText(getBaseContext(), "Login Cancelled", Toast.LENGTH_SHORT).show();
Log.d("i am in ", "cancel method");
// Toast.makeText(getApplicationContext(),"Login as cancelled",Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException e) {
Log.d("i am in ", "error method");
Toast.makeText(getApplicationContext(), "Internet Error occurred Please try again latter", Toast.LENGTH_SHORT).show();
/* Log.v("LoginActivity", e.getCause().toString());*/
}
});
private void RequestData() {
graphRequest = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
String emailId;
String profilePicUrl;
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
JSONObject json = response.getJSONObject();
if (response != null) {
try {
JSONObject data = response.getJSONObject();
username = json.getString("name");
emailId = json.getString("email");
}
catch (Exception e) {
e.printStackTrace();
}
}
CallingRetrofit(emailId,profilePicUrl);
LoginManager.getInstance().logOut();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,picture");
graphRequest.setParameters(parameters);
graphRequest.executeAsync();
}
In CallingRetrofit function I'm passing intent to home screen if he is a authorized user.

Profile.getCurrentProfile() return only my profile, all the rest are null

I'm trying to build a simple login to facebook app (with FB api v4.0)and retrieve some data about the user, but for some reason I success to login and get data only from my personal facebook profile, if tried to login with other users profile I'm getting null. (I change the setting in facebook developer to public app).
this is some of my loginButton_Fragment:
private CallbackManager callbackManager;
private FacebookCallback<LoginResult> facebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
Log.d("koko",accessToken.toString() );
if (profile != null){
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
user_birthDay = object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,birthday");
request.setParameters(parameters);
request.executeAsync();
user_name = profile.getName();
user_id = profile.getId();
Log.d("koko","first " +user_name + " " + user_id + " " + user_birthDay );
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
comm.respone(user_name, user_id, user_birthDay);
}
}, 500);
}
}
#Override
public void onCancel () {
}
#Override
public void onError (FacebookException e){
}
};
Each time I login, I'm getting inside the onSuccess, but if its not my personal profile so the profile its null.
set read permissions mButtonLogin.setReadPermissions(Arrays.asList("email,public_profile","user_birthday"));
try like this
mButtonLogin.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("status", "onSuccess");
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
try {
String name = object.getString("name");
String email =object.getString("email");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,email,birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.d("status", "onCancel");
}
#Override
public void onError(FacebookException e) {
Log.d("status", "onError " + e);
}
}
);
You need to acquire app specific permission from Facebook for retrieve user personal information's such as birthday, user_friends etc by submitting it for a review.
Invest few moments here .
If your app requests such permissions Facebook will have to review how your app uses it.
You will get public_profile as it's default .
Check this & this .

I need to wait untill i didnt get response and all data in android fb sdk

I want to wait until onCompleted() of my callback function of a Request is not finished.
i have written below code:
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) {
// Application code
Log.v("LoginActivity",
response.toString());
try {
username = object
.getString("first_name");
emailid = object.getString("email");
gender = object.getString("gender");
bday = object.getString("birthday");
//new User().execute(emailid);
} catch (JSONException e) {
// TODO Auto-generated catch
// block
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields",
"id,first_name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
i need to wait until my request is not completed. and after getting all data like email , gender etc i want to execute my function new User().execute(emailid);
How can i wait until i didnt get all the data from response.?
-----FOLLOWING ANSWERS: How can I wait until the request IS completed to run my code?
put your code like this:
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
try {
... //put your code here, will only run if response is ok
} catch (Exception e) {
...
}
}[...]
you WILL have the data once the
#Override
public void onCompleted(JSONObject object,GraphResponse response) {[...]
has run because onSuccess has already run meaning the response was successful.
You won't get any response , if you make GraphRequest within onCompleted() function. So avoid making GraphRequest within onCompleted() function. GraphRequest must call from UI thread. So just make GraphRequest from any UI thread functions. Surely you will get response.

Categories

Resources