Facebook Integration Android: onCompleted(GraphJSONObjectCallback) block not executing - android

I am trying to build an app which fetches all photos from facebook profile and this code is in the UserProfileActivity. But the intent which starts this activity is inside GraphRequest onCompleted block. This block is never getting executed as I saw while debugging. I tried a lot to understand it and saw various posts and everywhere the code is like this.
public class MainActivity extends AppCompatActivity implements FacebookCallback<LoginResult>{
private LoginButton buttonLoginFacebook;
private TextView textViewMessage;
private CallbackManager callbackManager;
private String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
buttonLoginFacebook = (LoginButton)findViewById(R.id.buttonLoginFacebook);
buttonLoginFacebook.setReadPermissions(Arrays.asList("public_profile, user_photos, user_posts"));
textViewMessage = (TextView)findViewById(R.id.textViewMessage);
buttonLoginFacebook.registerCallback(callbackManager,this);
}
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.e(TAG,object.toString());
Log.e(TAG,response.toString());
try{
String userId = object.getString("id");
URL profilePicture = new URL("https://graph.facebook.com/" + userId + "/picture?width=500&height=500");
String fullName="";
if(object.has("first_name"))
fullName += object.getString("first_name");
if(object.has("last_name"))
fullName += " " + object.getString("last_name");
Intent intent = new Intent(MainActivity.this,UserProfileActivity.class);
intent.putExtra("name",fullName);
intent.putExtra("imageUrl",profilePicture.toString());
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
textViewMessage.setText("Login attempt cancelled");
}
#Override
public void onError(FacebookException error) {
textViewMessage.setText("Login attempt failed");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
The code is never getting inside the onCompleted block. Thus the intent for UserProfileActivity is never getting executed. I am a little new to Facebook Sdk so any help would be appreciated.

its working for me
LoginManager.getInstance().registerCallback(mCallbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult success) {
// TODO Auto-generated method stub
Log.d("facebookLogin", "successful"
+ success.getRecentlyGrantedPermissions()
.toString() + " " + success.toString());
AccessToken token = success.getAccessToken();
if (token == null) {
Log.e("FBaccessToken", "null");
} else {
Log.d("FBAccesstoken", token.toString());
getFBMeData(token);
}
}
#Override
public void onError(FacebookException e) {
if (e instanceof FacebookException) {
if (AccessToken.getCurrentAccessToken() != null) {
LoginManager.getInstance().logOut();
}
}
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Log.d("facebookLogin", "canceled by user");
}
});
}
public void getFBMeData(AccessToken atoken) {
Profile.fetchProfileForCurrentAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
// TODO Auto-generated method stub
if (object != null) {
Log.d("FBGraphJSONObject", object.toString());
if(Profile.getCurrentProfile()!=null) {
FBdata.put("fbid", Profile.getCurrentProfile()
.getId());
FBdata.put("fname", Profile.getCurrentProfile()
.getFirstName());
FBdata.put("lname", Profile.getCurrentProfile()
.getLastName());
String gender = object.optString("gender");
String dob = object.optString("birthday");
String locationName = "";
JSONObject location = object
.optJSONObject("location");
if (location != null) {
locationName = location.optString("name");
}
String pictureUrl = "", email = "";
JSONObject picture = object
.optJSONObject("picture");
JSONObject data = picture.optJSONObject("data");
try {
email = URLDecoder.decode(
object.optString("email"), "UTF-8");
if (picture != null) {
pictureUrl = URLDecoder.decode(
data.optString("url"), "UTF-8");
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FBdata.put("photo", pictureUrl);
FBdata.put("address", locationName);
FBdata.put("dob", dob);
FBdata.put("gender", gender);
FBdata.put("email", email);
}
}
});
Bundle params = new Bundle();
params.putString("fields", "gender,email,birthday,location,picture");
request.setParameters(params);
request.executeAsync();
}

I had the same problem, The Issue was android.os.NetworkOnMainThreadException,So Make Sure You Call Network Request in a Separate Thread.

Related

Can't get name and email from facebook

I'm trying to get name and email from facebook login.
I'm using: compile 'com.facebook.android:facebook-android-sdk:4.+'
I can get into onSuccess but the code does not get into GraphRequest and I think that's why I can't get name and email (I'd also like get Profile picture)
I got the autogenerated code (GraphRequest) from facebook developer Explorer Api Graph
public class LoginActivity
{
LoginButton buttonLoginFacebook;
#Nullable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
buttonLoginFacebook = (LoginButton) findViewById(R.id.connectWithFbButton);
buttonLoginFacebook.setReadPermissions(Arrays.asList(
"public_profile", "email"));
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
FacebookSdk.addLoggingBehavior(LoggingBehavior.REQUESTS);
buttonLoginFacebook.setOnClickListener(this);
buttonLoginFacebook.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
//----->THE CODE JUMPS FROM HERE
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
mensajeFACEBOOK="TRYING TO GET NAME";
}
});
//----->TO HERE
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,first_name,last_name");
request.setParameters(parameters);
request.executeAsync();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
}
This is how i do it. Hope this helps.
private void registerCallBackMethod(){
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
final String accessToken = loginResult.getAccessToken().getUserId();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject,
GraphResponse response) {
// Getting FB User Data and checking for null
Bundle facebookData = getFacebookData(jsonObject);
String email = "";
String first_name = "";
String last_name = "";
String profile_pic = "";
if (facebookData.getString("email") != null && !TextUtils.isEmpty(facebookData.getString("email")))
email = facebookData.getString("email");
else
email = "";
if (facebookData.getString("first_name") != null && !TextUtils.isEmpty(facebookData.getString("first_name")))
first_name = facebookData.getString("first_name");
else
first_name = "";
if (facebookData.getString("last_name") != null && !TextUtils.isEmpty(facebookData.getString("last_name")))
last_name = facebookData.getString("last_name");
else
last_name = "";
if (facebookData.getString("profile_pic") != null && !TextUtils.isEmpty(facebookData.getString("profile_pic")))
profile_pic = facebookData.getString("profile_pic");
else
profile_pic = "";
sendValues(first_name+" "+last_name,email, "", "", accessToken, "Facebook",profile_pic);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,first_name,last_name,email,gender");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel () {
Log.d("TAG", "Login attempt cancelled.");
}
#Override
public void onError (FacebookException e){
e.printStackTrace();
Log.d("TAG", "Login attempt failed.");
deleteAccessToken();
}
}
);
}
private Bundle getFacebookData(JSONObject object) {
Bundle bundle = new Bundle();
try {
String id = object.getString("id");
URL profile_pic;
try {
profile_pic = new URL("https://graph.facebook.com/" + id + "/picture?type=large");
Log.i("profile_pic", profile_pic + "");
bundle.putString("profile_pic", profile_pic.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
bundle.putString("idFacebook", id);
if (object.has("first_name"))
bundle.putString("first_name", object.getString("first_name"));
if (object.has("last_name"))
bundle.putString("last_name", object.getString("last_name"));
if (object.has("email"))
bundle.putString("email", object.getString("email"));
if (object.has("gender"))
bundle.putString("gender", object.getString("gender"));
} catch (Exception e) {
Log.d("TAG", "BUNDLE Exception : "+e.toString());
}
return bundle;
}
private void deleteAccessToken() {
AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
if (currentAccessToken == null){
//User logged out
LoginManager.getInstance().logOut();
}
}
};
}
Actually GraphRequest.executeAsync() is an async method with a callback onCompleted so to read the data you need to do it inside the callback.
buttonLoginFacebook.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) {
//Read the data you need from the GraphResponse here like this:
try {
String firstName = response.getJSONObject().getString("first_name");
String lastName = response.getJSONObject().getString("last_name");
String email = response.getJSONObject().getString("email");
String id = response.getJSONObject().getString("id");
String picture = response.getJSONObject().getJSONObject("picture").getJSONObject("data").getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,first_name,last_name,picture.width(150).height(150)");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
Also included the profile picture field picture.width(150).height(150) as you asked

I want to fetch data from facebook's profile. I am able to login but its not calling the onSuccess(). in Android studio

I want to fetch data of user like name, email and other details. I am able to login using facbook API. But I foound out the onSuccess() method is not executing. however it shows me log in.
public class SignInUpActivity extends AppCompatActivity {
private CallbackManager callbackManager;
LoginButton fbLoginBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//intialize fb sdk
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_sign_in_up);
fbLoginBtn = (LoginButton) findViewById(R.id.ObiNoID_SignIn_SignUpActivity_btn_fb_login);
// setting permission for fb accounts
fbLoginBtn.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends"));
callbackManager = CallbackManager.Factory.create();
fbLoginBtn.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) {
try {
String email = object.getString("email");
String birthday = object.getString("birthday");
Toast.makeText(SignInUpActivity.this,email+birthday,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onCancel() {
Toast.makeText(SignInUpActivity.this, "cancelled", Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(SignInUpActivity.this, "error", Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);// will call the call
}
}
I am a begginer please help me solve the problem.
try this,
private void connectToFacebook() {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json, GraphResponse response) {
// Application code
if (response.getError() != null) {
System.out.println("ERROR");
} else {
System.out.println("Success");
String jsonresult = String.valueOf(json);
System.out.println("JSON Result" + jsonresult);
String fbUserId = json.optString("id");
String fbUserFirstName = json.optString("name");
String fbUserEmail = json.optString("email");
String fbUserProfilePics = "http://graph.facebook.com/" + fbUserId + "/picture?type=large";
}
Log.v("LoginActivity", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
// App code
// Log.v("LoginActivity", "" + exception);
Toast.makeText(LoginActivity.this, "" + exception, Toast.LENGTH_LONG).show();
}
});
}

How to get Profile picture,primary e-mail,Facebook link of a user from an android App in Facebook SDK 4.5?

I am using latest Facebook sdk for android in my applicaton.
public class MainActivity extends AppCompatActivity {
public static CallbackManager callbackmanager;
private AccessTokenTracker mTokenTracker;
private ProfileTracker mProfileTracker;
Button fb_login;
private boolean fb_signincllicked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
fb_login = (Button) findViewById(R.id.fb_login_button);
fb_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onFblogin(true);
}
});
}
public void onFblogin(boolean fb_btn) {
fb_signincllicked = fb_btn;
callbackmanager = CallbackManager.Factory.create();
// setupTokenTracker();
// setupProfileTracker();
// mTokenTracker.startTracking();
// mProfileTracker.startTracking();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
LoginManager.getInstance().registerCallback(callbackmanager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// AccessToken accessToken = loginResult.getAccessToken();
// Profile profile = Profile.getCurrentProfile();
final Set<String> deniedPermissions = loginResult.getRecentlyDeniedPermissions();
GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json, GraphResponse response) {
if (response.getError() != null) {
// handle error
} else {
try {
// if (deniedPermissions.contains("email")) {
// LoginManager.getInstance().logInWithReadPermissions(Login_Activity.this, Arrays.asList("email"));
// }
JSONObject jsonObject = new JSONObject();
if (jsonObject.has("picture")) {
String profilePicUrl = jsonObject.getJSONObject("picture").getJSONObject("data").getString("url");
System.out.println("111015:profilePicUrl" + profilePicUrl);
} else {
System.out.println("111015:profilePicUrl" + "No Data");
}
jsonObject.put("full_name", json.getString("name"));
Toast.makeText(getApplicationContext(), json.get("id").toString() + json.getString("name"), Toast.LENGTH_LONG).show();
jsonObject.put("device_id", Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID));
jsonObject.put("fb_id", json.getString("id"));
jsonObject.put("signuptype", "1");
Intent i = new Intent(getBaseContext(), Profile.class);
i.putExtra("prof_name", json.getString("name"));
i.putExtra("fb_id", json.getString("id"));
startActivity(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}).executeAsync();
}
#Override
public void onCancel() {
Log.d("Cancel", "On cancel");
}
#Override
public void onError(FacebookException error) {
Log.d("Error", error.toString());
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (fb_signincllicked) {
callbackmanager.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onStop() {
super.onStop();
// mTokenTracker.stopTracking();
// mProfileTracker.stopTracking();
}
// private void setupTokenTracker() {
// mTokenTracker = new AccessTokenTracker() {
// #Override
// protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
// Log.d("VIVZ", "" + currentAccessToken);
// }
// };
// }
//
// private void setupProfileTracker() {
// mProfileTracker = new ProfileTracker() {
// #Override
// protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
// Log.d("VIVZ", "" + currentProfile);
// }
// };
// }
}
After success full login(which succeeded) i want to go to another activity.There i want to show the following,
Facebook profile picture in a custom image view(not in the image
view which Facebook provided).
Primary-Email
Phone Number(If user provided in Face Book)
Facebook link of the user.
Please help me. Thanks in advance.
On your onActivityCreated() put this code :
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
updateWithToken(AccessToken.getCurrentAccessToken());
}
then here is my code which i'm currently using it to make facebook login :
private void updateWithToken(AccessToken currentAccessToken) {
mTokenTracker.startTracking();
mProfileTracker.startTracking();
if (currentAccessToken != null) {
String accessToken = currentAccessToken
.getToken();
Log.i("accessToken", accessToken);
GraphRequest request = GraphRequest.newMeRequest(
currentAccessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
Log.i("LoginActivity",
response.toString());
try {
String id = object.getString("id");
try {
URL profile_pic = new URL(
"http://graph.facebook.com/" + id + "/picture?type=large");
Log.i("profile_pic",
profile_pic + "");
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (!sessionManagerFacebook.isLoggedIn()) {
sessionManagerFacebook.createLoginSession(object.getString("email"), getResources().getConfiguration().locale.toString());
if (cameFromQuestionExtra != null && cameFromQuestionExtra.getString("cameFromQuestion").equals("yes")) {
getActivity().setResult(1);
getActivity().finish();
}
//startActivity(new Intent(getActivity(), MainActivity.class));
} else {
user = sessionManagerFacebook.getUserDetails();
startActivity(new Intent(getActivity(), MainActivity.class));
}
getActivity().finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields",
"id,name,email,gender");
request.setParameters(parameters);
request.executeAsync();
}
}
And on your second activity u just have to make new profile variable :
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
Toast.makeText(MainActivity.this, profile.getName(), Toast.LENGTH_SHORT).show();
loadImages(profile.getProfilePictureUri(120, 120).toString());
profileName.setText(profile.getName());
mDrawer.getMenu().findItem(R.id.nav_myAccount).setVisible(false);
Bundle extra = getIntent().getExtras();
String email;
if (extra != null) {
email = extra.getString("email");
profileEmail.setText(email);
Toast.makeText(MainActivity.this, email, Toast.LENGTH_SHORT).show();
} else if (sessionManagerFacebook.isLoggedIn()) {
profileEmail.setText(userFacebook.get(SessionManagerFacebook.KEY_EMAIL));
Toast.makeText(MainActivity.this, userFacebook.get(SessionManagerFacebook.KEY_EMAIL), Toast.LENGTH_SHORT).show();
}
}
https://developers.facebook.com/docs/reference/android/current/class/Profile/

In Android, Facebook API V2.4 is not returning email id whereas V2.3 is returning. How to get email id in V2.4?

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

Issue getting Facebook information

I want facebook profile information in my code. This code works Log.e("in try start", "tryyyyyyyyy"); until here but after that not even single log is executed.
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
public void loginToFacebook() {
// mPrefs = getPreferences(SharedPreferences.);
// String access_token = mPrefs.getString("access_token", null);
//long expires = mPrefs.getLong("access_expires", 0);
// if (access_token != null) {
// facebook.setAccessToken(access_token);
// }
// if (expires != 0) {
// facebook.setAccessExpires(expires);
// }
if (!facebook.isSessionValid()) {
facebook.authorize(getActivity(),
new String[] { "email", "publish_actions" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
Toast.makeText(getActivity(), "hiiiiii", Toast.LENGTH_SHORT).show();
//mPrefs=getSharedPreferences("data", getActivity().MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
Log.e("getProfileInformation entry", "getProfileInformation");
getProfileInformation();
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
});
}
}
public void getProfileInformation() {
Toast.makeText(getActivity(), "byeeeeeee", Toast.LENGTH_SHORT).show();
Log.e("getProfileInformation start", "getProfileInformation");
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
Log.e("in try start", "tryyyyyyyyy");
JSONObject profile = new JSONObject(json);
// getting name of the user
Log.d("profile", ""+profile);
fb_name = profile.getString("name");
// getting email of the user
fb_email = profile.getString("email");
Log.d("fb_name", "naem"+fb_name+"emial"+fb_email);
//fb_login=true;
// fb_Image = getUserPic(fb_email);
// LoginFuction();
} catch (JSONException e) {
e.printStackTrace();
Log.e("catchhhhhh", ""+e.getMessage());
}
}
public Bitmap getUserPic(String userID) {
String imageURL;
Bitmap bitmap = null;
Log.d("TAG", "Loading Picture");
imageURL = "http://graph.facebook.com/"+userID+"/picture?type=small";
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
} catch (Exception e) {
Log.d("TAG", "Loading Picture FAILED");
e.printStackTrace();
}
return bitmap;
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
This code does not give me any name or emailId.
-Hello Abhishek !
- I have tried using Facebook sdk4.+ and i am getting profile info perfectly.
-Firs of all add below code into your oncreate method before setcontentview
FacebookSdk.sdkInitialize(getApplicationContext());
-Then Create you Callbackmanager using below code:-
callbackManager = CallbackManager.Factory.create();
-Add Permissions using below code:-
permission.add("publish_actions");
-Below code is used for Login
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
act,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
if (!TextUtils.isEmpty(object.toString())) {
try {
JSONObject jresJsonObject = new JSONObject(object.toString());
String id = "", name = "", gender = "";
if (!(jresJsonObject.isNull("id"))) {
id = jresJsonObject.getString("id");
}
if (!(jresJsonObject.isNull("gender"))) {
gender = jresJsonObject.getString("gender");
if (gender.equals("male")) {
gender = "0";
} else {
gender = "1";
}
}
if (!(jresJsonObject.isNull("name"))) {
name = jresJsonObject.getString("name");
}
} catch (Exception e) {
}
}
Log.e("graphrequest", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,gender,link");
request.setParameters(parameters);
request.executeAndWait();
}
#Override
public void onCancel() {
Log.i("", "Access Token:: " + "loginResult.getAccessToken()");
}
#Override
public void onError(FacebookException exception) {
Log.i("", "Access Token:: " + "loginResult.getAccessToken()");
}
});
LoginManager.getInstance().logInWithPublishPermissions(this, permission);
-Last but no least add below code in your OnActivitResult
callbackManager.onActivityResult(requestCode, resultCode, data);
NOTE:- This is using latest Facebook sdk
-Please inform me if it is not usefull or you are still getting issue in this.

Categories

Resources