Can't Get Location and Email Using Facebook API

Can't get location and email using Facebook API

The issue is that you have not asked for permissions:

authButton.setReadPermissions(Arrays.asList("user_likes", "user_status","email","user_birthday"));

However, you are using an older Facebook SDK, while the newest SDK is 4.0.+. Below, I will give you a full sample code for Facebook login, based on the newest API. Keep in mind that you first have to add your application in developers.facebook as the documentation mentions out.

public class LoginActivity extends ActionBarActivity{

@Override
protected void onActivityResult(int requestCode, int responseCode, Intent data)
{
super.onActivityResult(requestCode, responseCode, data);
callbackManager.onActivityResult(requestCode, responseCode, data);
}

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.loginFaceBook_button);
List<String> permissionNeeds = Arrays.asList("user_photos", "email", "user_birthday", "public_profile");
loginButton.setReadPermissions(permissionNeeds);

loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
{
@Override
public void onSuccess(LoginResult loginResult)
{
System.out.println("onSuccess");
GraphRequest request = GraphRequest.newMeRequest
(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback()
{
@Override
public void onCompleted(JSONObject object, GraphResponse response)
{
// Application code
Log.v("LoginActivity", response.toString());
//System.out.println("Check: " + response.toString());
try
{
String id = object.getString("id");
String name = object.getString("name");
String email = object.getString("email");
String gender = object.getString("gender");
String birthday = object.getString("birthday");
System.out.println(id + ", " + name + ", " + email + ", " + gender + ", " + 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()
{
System.out.println("onCancel");
}

@Override
public void onError(FacebookException exception)
{
System.out.println("onError");
Log.v("LoginActivity", exception.getCause().toString());
}
});
}
}

If you want to use Fragment instead of ActionBarActivity, the just add loginButton.setFragment(this); right after your permission line.

manifest.xml:

<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
<!-- your other attrs..-->
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/app_id"/> <!-- Get this one from developers.facebook -->
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:label="@string/app_name"/>

You will need to add to your application a hash key too. Here is a way to do this with code:

try
{
//paste Your package name at the first parameter
PackageInfo info = getPackageManager().getPackageInfo("PUT_YOUR_PACKAGE_NAME_HERE",
PackageManager.GET_SIGNATURES);
for (android.content.pm.Signature signature : info.signatures)
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String sign = Base64.encodeToString(md.digest(), Base64.DEFAULT);
Log.e("MY KEY HASH:", sign);
Toast.makeText(getApplicationContext(),sign, Toast.LENGTH_LONG).show();
}
}
catch (PackageManager.NameNotFoundException e)
{
}
catch (NoSuchAlgorithmException e)
{
}

After it prints you out the hash key, you copy paste it to your facebook.developer account, where your project is located.

In grandle, you should add jcenter in repositories and also add compile 'com.facebook.android:facebook-android-sdk:4.0.0' in dependecies.

buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects
{
repositories {
jcenter()
/*more project attrs..*/
}
}

And the other grandle file:

apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
applicationId "YOUR_PACKAGE_NAME"
minSdkVersion 14
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
}

Edit:

In order to track the user's location, you will need a GPS Tracker, something like this. "user_location" permission does not return a lon, lat, but a Page object, which I think is not what you want. So, your permissions should be List<String> permissionNeeds = Arrays.asList("user_photos", "email", "user_birthday", "public_profile"); and now you should be able to retrieve user's email

Facebook Graph API won't return email address

After i got my bug report marked as duplicate, and i read all posts and links there, i got what caused this problem for me and how to fix.

The Problem
Facebook seems to sometimes forget what your primary e-mail is on the graph API (But it still there in the preferences.)

Solution
The user affected must remove the e-mail, save settings, then re-add the address, re-confirm, then make it primary. This fixed my account both on my sandbox app, and other apps where Facebook login don't used to work.

FB API GRAPH: why I can't catch the user email?

https://developers.facebook.com/docs/reference/javascript/FB.login/v3.2

Ask for the email permission in the login process:

FB.login((response) => {
// handle the response
}, {scope: 'email'});

Also, you need to ask for the fields you want to get:

FB.api('/me', {fields: 'name,email'}, (response) => {
console.log(response.name + ', ' + response.email);
});

Make sure the user even has an Email, it´s not required. And make sure you actually get asked for the email permission in the login popup.

Side Note: I would just use console.log(response), so you can see the whole object instead of some undefined values.

Facebook Graph API, how to get users email?

The only way to get the users e-mail address is to request extended permissions on the email field. The user must allow you to see this and you cannot get the e-mail addresses of the user's friends.

http://developers.facebook.com/docs/authentication/permissions

You can do this if you are using Facebook connect by passing scope=email in the get string of your call to the Auth Dialog.

I'd recommend using an SDK instead of file_get_contents as it makes it far easier to perform the Oauth authentication.



Related Topics



Leave a reply



Submit