With new api and your custom button for facebook you can use below code:
put below gradle in your gradle file:
compile 'com.facebook.android:facebook-android-sdk:4.20.0'
Newer sdk does not need initializaion .
private CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(LoginActivity.this);//Is now depricated
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
}
onActivityResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Button Click:
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.btn_f_sign_in_login:
LoginManager.getInstance().logInWithReadPermissions(
this,
Arrays.asList("user_friends", "email", "public_profile"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
setFacebookData(loginResult);
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException exception) {
}
});
break;
}
}
setFacebookData:
private void setFacebookData(final LoginResult loginResult)
{
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 firstName = response.getJSONObject().getString("first_name");
String lastName = response.getJSONObject().getString("last_name");
String gender = response.getJSONObject().getString("gender");
Profile profile = Profile.getCurrentProfile();
String id = profile.getId();
String link = profile.getLinkUri().toString();
Log.i("Link",link);
if (Profile.getCurrentProfile()!=null)
{
Log.i("Login", "ProfilePic" + Profile.getCurrentProfile().getProfilePictureUri(200, 200));
}
Log.i("Login" + "Email", email);
Log.i("Login"+ "FirstName", firstName);
Log.i("Login" + "LastName", lastName);
Log.i("Login" + "Gender", gender);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email,first_name,last_name,gender");
request.setParameters(parameters);
request.executeAsync();
}
get Facebook Friends Who has downoaded your app:
replace parameters.putString("fields", "id,email,first_name,last_name");
with parameters.putString("fields", "id,email,first_name,last_name,friends");
Add below logic to get friends Data
if (object.has("friends")) {
JSONObject friend = object.getJSONObject("friends");
JSONArray data = friend.getJSONArray("data");
for (int i=0;i<data.length();i++){
Log.i("idddd",data.getJSONObject(i).getString("id"));
}
}