how uber app get mobile number from facebook in android - android

How could uber android application get my mobile number while facebook login
I am using Facebook login in my android app and i want user mobile number from facebook but i am not getting it following is my android code
private void FbInitialise() {
loginButton = (LoginButton) findViewById(R.id.fb_login);
callbackManager = CallbackManager.Factory.create();
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_friends"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
public void graphRequest(AccessToken token) {
GraphRequest request = GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
LoginType="FB";
String firstName = "";
String lastName = "";
String stremail = "";
String strmobile = "";
if (object.has("first_name")) {
firstName = object.getString("first_name");
}
if (object.has("last_name")) {
lastName = object.getString("last_name");
}if (object.has("email")) {
stremail = object.getString("email");
}
Intent intent=new Intent(SelectSocilaLoginActivity.this,ConfirmInfoActivity.class);
intent.putExtra("firstName",firstName);
intent.putExtra("lastName",lastName);
intent.putExtra("email",stremail);
intent.putExtra("parent","SocialLogin");
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle b = new Bundle();
b.putString("fields", "id, first_name, last_name, email,gender, birthday, location");
request.setParameters(b);
request.executeAsync();
}
please give me proper solution

Here is how I managed to extract mobile number from the Login user's profile:
public class UserAuth extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
private Context context;
private Button btnViewProfile;
//For User data
private String userId, userFirstName, userMiddleName, userLastName, userProfileImage, userEmail, userGender, userMobile, userBirthdate;
//For Facebook
private CallbackManager callbackManager;
LoginButton loginButton = null;
private ImageButton btnFacebook;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Enabling strict mode */
setStrictThreadMode();
//initializing facebook sdk
FacebookSdk.sdkInitialize(getApplicationContext());
//Initialize your view components available in the layout
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken,
AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile,
Profile newProfile) {
if (newProfile != null) {
userId = newProfile.getId();
userFirstName = newProfile.getFirstName();
userMiddleName = newProfile.getMiddleName();
userLastName = newProfile.getLastName();
userProfileImage = newProfile.getProfilePictureUri(400, 400).toString();
}
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
//To enable single thread at a time mode
private void setStrictThreadMode() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
protected void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
}
//This method initializes the facebook login button, sets the required permissions and changes its default background to our drawable
//It also registers the callback for the Login button
private void registerLoginButton() {
List<String> mPermissions = new ArrayList<>();
mPermissions.add("public_profile");
mPermissions.add("email");
mPermissions.add("user_birthday");
mPermissions.add("user_friends");
mPermissions.add("user_mobile_phone");
loginButton.setReadPermissions(mPermissions);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult result) {
GraphRequest request = GraphRequest.newMeRequest(result.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
userEmail = object.optString("email");
userGender = object.optString("gender");
userMobile = object.optString("mobile_phone");
String userBirthdate = object.optString("birthday");
logoutCurrentUser();
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
//This method is to end the current users session
private void logoutCurrentUser() {
LoginManager.getInstance().logOut();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
Observe we have added permission for fetching mobile number: mPermissions.add("user_mobile_phone");
Also, please remember that you will only get the mobile number if the user has made it public.
Hope this works for you.

Related

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

Getting user full name upon facebook login Android app

I am trying to add a facebook login to an android app. While the login button and logging in works fine, I am also trying to obtain the first and last name of the user when they log in. However, the String username always stays null. Below is the complete code of this activity:
public class FacebookLoginActivity extends BaseActivity {
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
private String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.fb_login_activity);
info = (TextView) findViewById(R.id.info);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
setData();
if(username != null) {
Intent intent = new Intent(FacebookLoginActivity.this, LoginActivity.class);
Bundle bundle = new Bundle();
bundle.putString("username", username);
intent.putExtras(bundle);
startActivity(intent);
}
}
#Override
public void onCancel() {
info.setText("Login attempt canceled.");
}
#Override
public void onError(FacebookException error) {
info.setText("Login attempt failed.");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private void setData(){
if(AccessToken.getCurrentAccessToken() != null){
final GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
if(AccessToken.getCurrentAccessToken()!=null){
try {
username = response.getJSONObject().getString("first_name")+ " " + response.getJSONObject().getString("last_name");
}
catch(JSONException e){
e.printStackTrace();
}
}
}
});
}
}
}

iam using facebook sdk 4.0 cannot login with facebook in fragment

iam using facebook sdk 4.0 cannot login with facebook in fragment
here is my code
fbLoginButton.registerCallback(mCallbackManager, new FacebookCallback < LoginResult > () {
#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("onSuccess");
String accessToken = loginResult.getAccessToken()
.getToken();
Log.d("accessToken", accessToken);
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.d("LoginActivity",
response.toString());
try {
String id = object.getString("id");
try {
URL profile_pic = new URL(
"http://graph.facebook.com/" + id + "/picture?type=large");
Log.d("profile_pic",
profile_pic + "");
} catch (MalformedURLException e) {
e.printStackTrace();
}
String name = object.getString("name");
String email = object.getString("email");
String gender = object.getString("gender");
String birthday = object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.d("cancel", "onCancel");
}
#Override
public void onError(FacebookException exception) {
System.out.println("onError");
Log.d("LoginActivity", exception.getCause().toString());
}
});
}
#Override
public void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
mCallbackManager.onActivityResult(requestCode, responseCode, data);
}
It never comes in onSucess or in error after log in .it does not change the log in button to logout.what is the problem is there other method to use it from fragment.
Make a method facebookLogIn() as:
public void facebookLogIn(){
FacebookCallback<LoginResult> loginResultFacebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Log.e("FB", String.valueOf(accessToken));
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
// name.setText("Witam " + profile.getName());
Toast.makeText(LogIn.this, profile.getFirstName(), Toast.LENGTH_SHORT).show();
Log.e("FB", "w");
}
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
};
callbackManager = CallbackManager.Factory.create();
LoginButton mBtnFacebook = (LoginButton) findViewById(R.id.login_button);
mBtnFacebook.setReadPermissions(Arrays.asList("public_profile", "user_friends"));
mBtnFacebook.registerCallback(callbackManager, loginResultFacebookCallback);
}
and call this method from your onCreate() method.
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
public MainFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
displayMessage(newProfile);
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
textView = (TextView) view.findViewById(R.id.textView);
loginButton.setReadPermissions("user_friends");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private void displayMessage(Profile profile) {
if (profile != null) {
textView.setText(profile.getName());
}
}
#Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}

How to get the email of a user from the facebook LoginButton widget?

How can I get the email of a user from the facebook LoginButton widget?
I am getting null. The App Id I am using is correct. I can also get the correct name, but the email is missing. I do have permissions.
This is my code:
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;
// ...
public class MainActivity extends FragmentActivity {
// ...
#Override
public void onCreate(Bundle savedInstanceState) {
//
LoginButton loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
userName.setText("Hello, " + user.getName());
Toast.makeText(getApplicationContext(),
"User Name is , " + user.getName(), Toast.LENGTH_LONG)
.show();
Toast.makeText(getApplicationContext(),
"Email Id is , " + user.getProperty("email") , Toast.LENGTH_LONG)
.show();
} else {
userName.setText("You are not logged");
}
}
});
}
// ...
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions","email","basic_info");
public void requestPermissions() {
Session s = Session.getActiveSession();
if (s != null)
s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS));
}
public class Login extends ActionBarActivity {
private CallbackManager callbackManager;
String emailid, gender, bday, username;
private LoginButton loginButton;
ProfilePictureView profilePictureView;
TextView info;
private AccessTokenTracker accessTokenTracker;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.login);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays
.asList("public_profile, email, user_birthday, user_friends"));
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
new fblogin().execute(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
class fblogin extends AsyncTask<AccessToken, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("wait.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(AccessToken... params) {
GraphRequest request = GraphRequest.newMeRequest(params[0],
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
Log.v("LoginActivity", response.toString());
try {
username = object.getString("first_name");
emailid = object.getString("email");
gender = object.getString("gender");
bday = object.getString("birthday");
} 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.executeAndWait();
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
This method work in Async manner.
Its Done . !!
You can fetch user email by sending Request.newMeRequest request. For this you need UiLifecycleHelper callback
UiLifecycleHelper fbUiHelper = new UiLifecycleHelper(this, fbUiHelperCallback);
private Session.StatusCallback fbUiHelperCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
getUserData(session, state);
}
private void getUserData(Session session, SessionState state) {
if (state.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (response != null) {
String name = user.getName();
// If you asked for email permission
String gender = (String) user.getProperty("gender");
String email = (String) user.getProperty("email");
}
}
}).executeAsync();
}
}

Get profile data from Facebook SDK on Android always return Null. Why?

i just learned about facebook SDK on android. I already search on stackoverflow and facebook developer guide for login, but i still stuck when get profile data from facebook sdk. i try implement solution from : unable get profile and Get email, but still stuck.
There is my code :
public class HomeLoginActivity extends Activity {
LoginButton btnFacebook;
CallbackManager callbackManager = CallbackManager.Factory.create();
ProfileTracker profTrack;
AccessTokenTracker accessTokenTracker;
TextView welcomeText;
FacebookCallback<LoginResult> mFacebookCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
setContentView(R.layout.activity_home_login);
welcomeText = (TextView) findViewById(R.id.welcome_id);
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
// App code
Log.d("current token", "" + currentAccessToken);
//}
}
};
profTrack = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(
Profile oldProfile,
Profile currentProfile) {
// App code
Log.d("current profile", "" + currentProfile);
welcomeText.setText(constructWelcomeMessage(currentProfile));
}
};
mFacebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
welcomeText.setText(constructWelcomeMessage(profile));
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
try {
String id=object.getString("id");
String name=object.getString("name");
String email=object.getString("email");
String gender=object.getString("gender");
Stringbirthday=object.getString("birthday");
//do something with the data here
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
accessTokenTracker.startTracking();
profTrack.startTracking();
//Button Facebook
btnFacebook = (LoginButton) findViewById(R.id.btnFacebook);
btnFacebook.setReadPermissions("public_profile", "user_friends");
btnFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions((Activity) v.getContext(),Arrays.asList("public_profile", "user_friends"));
}
});
btnFacebook.registerCallback(callbackManager, mFacebookCallback);
}
// ennd on create
private String constructWelcomeMessage(Profile profile) {
StringBuffer stringBuffer = new StringBuffer();
if (profile != null) {
stringBuffer.append("Welcome " + profile.getName());
}
else {
stringBuffer.append("NULL Profile");
}
return stringBuffer.toString();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onResume() {
super.onResume();
AccessToken.getCurrentAccessToken();
Log.d("resume current token", "" + AccessToken.getCurrentAccessToken());
Profile.fetchProfileForCurrentAccessToken();
}
#Override
public void onStop() {
super.onStop();
profTrack.stopTracking();
accessTokenTracker.stopTracking();
}
#Override
public void onDestroy() {
super.onDestroy();
accessTokenTracker.stopTracking();
profTrack.stopTracking();
}
}
and there is my log cat :
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
at com.twiscode.gimme.HomeLoginActivity$3$1.onCompleted(HomeLoginActivity.java:100)
at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:298)
at com.facebook.GraphRequest$5.run(GraphRequest.java:1246)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Try this sample code to get profile info
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
// login ok get access token
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
if (BuildConfig.DEBUG) {
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk
.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
System.out
.println("AccessToken.getCurrentAccessToken()"
+ AccessToken
.getCurrentAccessToken()
.toString());
Profile.getCurrentProfile().getId();
Profile.getCurrentProfile().getFirstName();
Profile.getCurrentProfile().getLastName();
Profile.getCurrentProfile().getProfilePictureUri(50, 50);
//String email=UserManager.asMap().get(“email”).toString();
}
}
});
request.executeAsync();
/* Bundle parameters = new Bundle();
parameters
.putString("fields",
"id,firstName,lastName,name,email,gender,birthday,address");
request.setParameters(parameters);
Intent loginintent = new Intent(getActivity(),
EditProfile.class);
startActivity(loginintent);
System.out.println("XXXX " + getId());
*/
makeJsonObjReq();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
return view;
I was facing the same error and finally found the solution. Basically you have to know first what is causing this crash/NullPointerException. So to find out what is causing this exception, make your onComplete block of code look like below:
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.v("LoginActivity Response ", response.toString());
}
});
Now, run your app and try logging in using the FB button. Keep checking your logcat and soon you will see a line like below:
V/LoginActivity Response: {Response: responseCode: 200, graphObject: {"id":"10206735777938523","name":"Rohit Paniker","email":"rohit.paniker.1990#gmail.com","gender":"male"}, error: null}
I was using the "age" permission which was causing the NullPointerException in ID, Name, Email and all permissions which i got to know from the above logcat output. As per the output i understood why the crash was happening and I removed the object.getString("age") and ran the app again, worked perfectly without crash and I got all data from ID to Name and email!
See my working code below to get profile details FB SDK 4
//Initialize Facebook SDK
FacebookSdk.sdkInitialize(getApplicationContext());
//if the facebook profile is changed, below code block will be called
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
if(currentProfile != null){
fbUserId = currentProfile.getId();
if(!sharedPreferences.contains("UserName")){
editor.putString("UserName",currentProfile.getFirstName()+" "+currentProfile.getLastName());
}
if(!sharedPreferences.contains("FbId")){
editor.putString("FbId",currentProfile.getId());
}
if(!sharedPreferences.contains("ProfilePicture")){
editor.putString("ProfilePicture",currentProfile.getProfilePictureUri(100,100).toString());
}
editor.commit();
}
}
};
//when new fb user logged in , below code block will be called
AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken accessToken, AccessToken accessToken2) {
System.out.println("acesstoken trackercalled");
}
};
//set layout resource
setContentView(R.layout.activity_login);
//fb login button
loginButton = (LoginButton) findViewById(R.id.connectWithFbButton);
//set fb permissions
loginButton.setReadPermissions(Arrays.asList("public_profile,email"));
//call the login callback manager
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
profile = Profile.getCurrentProfile();
if(profile != null){
fbUserId = profile.getId();
if(!sharedPreferences.contains("UserName")){
editor.putString("UserName",profile.getFirstName()+" "+profile.getLastName());
}
if(!sharedPreferences.contains("FbId")){
editor.putString("FbId",profile.getId());
}
if(!sharedPreferences.contains("ProfilePicture")){
editor.putString("ProfilePicture",profile.getProfilePictureUri(20,20).toString());
}
editor.commit();
}
goToNewActivity();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
Please try with this code :
LoginManager.getInstance().logInWithReadPermissions(Activity.this,
Arrays.asList("public_profile","email"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
public void onSuccess(LoginResult loginResult) {
if (AccessToken.getCurrentAccessToken() != null) {
Log.e("idfb",""+loginResult.getAccessToken().getUserId());
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
try {
Log.i("Response",response.toString());
String email = response.getJSONObject().getString("email");
String name = response.getJSONObject().getString("name");
String id = response.getJSONObject().getString("id");
String imgUrl = "https://graph.facebook.com/" + id + "/picture?type=large";
Log.i("Login" + "Email", "");
Log.i("Login"+ "FirstName", name);
Log.i("Login" + "Id", id);
} catch (JSONException e) {
e.printStackTrace();
Log.e("errorfb",""+e);
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email,name,link");
request.setParameters(parameters);
request.executeAsync();
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});

Categories

Resources